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

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

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳