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
Related Articles
Deepen your understanding with these curated continuations.
Convert array to an object in JavaScript
This article explains simplest and quickest way to convert array to an object in JavaScript. Using widely accepted spread operator `...` makes easy to do it.
How to Update an Array Element in JavaScript
Learn the simplest ways to update array elements in JavaScript. This guide explains how to use assignment operators and modern methods to modify array values.
Flatten an Array One Level Deep in Javascript
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.