How to use the Spread operator In Javascript
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.
Example: The below example uses the spread operator to add element at the start of an array.
let arr = [66, 85, 19, 7];
console.log(`Array Elements Before
element addition:
${arr}`);
arr = [34, ...arr];
console.log(`Array Elements After
element addition:
${arr}`);
Output
Array Elements Before element addition: 66,85,19,7 Array Elements After element addition: 34,66,85,19,7
Add new elements at the beginning of an array using JavaScript
In this article, we will learn how to add new elements at the beginning of an array using JavaScript. We can do this by using the following methods:
Table of Content
- Using the Array unshift() method
- Using array.splice method
- Using the Spread operator
- Using Array concat() Method
- Using array destructuring