M
MeshWorld.
JavaScript Tutorial 1 min read

How to add an element to starting of an array with ES6

Vishnu Damwala
By Vishnu Damwala

The spread operator ..., introduced first in ES6 became one of the most popular and favourite feature among the developers.

It is much widely accepted that a proposal was made to extend its functionalities to objects, prior it only worked on arrays.

Lets use the spread operator to add element to the starting of an array.

Example with food emoji

let fruits = ["๐Ÿ‡", "๐Ÿ‰", "๐Ÿ", "๐Ÿ“", "๐Ÿฅ", "๐ŸŠ", "๐ŸŽ", "๐Ÿ"];
console.log(fruits);
// Output โ†’ ["๐Ÿ‡", "๐Ÿ‰", "๐Ÿ", "๐Ÿ“", "๐Ÿฅ", "๐ŸŠ", "๐ŸŽ", "๐Ÿ"]

console.log(fruits.length);
// Output โ†’ 8

fruits = ["๐Ÿฅญ", ...fruits];

console.log(fruits.length);
// Output โ†’ 9

console.log(fruits);
// Output โ†’ ["๐Ÿฅญ", "๐Ÿ‡", "๐Ÿ‰", "๐Ÿ", "๐Ÿ“", "๐Ÿฅ", "๐ŸŠ", "๐ŸŽ", "๐Ÿ"]

Example with sports emojis

Below example adds multiple elements to the start of an array

let sports = ["โšพ", "๐Ÿ€", "๐ŸŽพ", "๐ŸŽณ", "๐Ÿ‘", "๐Ÿธ", "๐ŸฅŠ"];
console.log(sports);
// Output โ†’ ["โšพ", "๐Ÿ€", "๐ŸŽพ", "๐ŸŽณ", "๐Ÿ‘", "๐Ÿธ", "๐ŸฅŠ"]

console.log(sports.length);
// Output โ†’ 7

sports = ["โšฝ", "๐Ÿฅ", ...sports];

console.log(sports.length);
// Output โ†’ 9

console.log(sports);
// Output โ†’ ["โšฝ", "๐Ÿฅ", "โšพ", "๐Ÿ€", "๐ŸŽพ", "๐ŸŽณ", "๐Ÿ‘", "๐Ÿธ", "๐ŸฅŠ"]

Happy coding