Why Use JavaScript's Spread Syntax?
JavaScript's spread syntax consists of ellipsis (...) and is quite useful when it comes to copying values into arrays and objects. Its use makes working with arrays and objects faster and more readable.
Copying Items From Ane Array to Another
Let's say we want to copy items from arr1 containing the values [1, 2, 3] into a new array arr2 with added values [4, 5, 6]. There are several ways to make arr2 have an end result of [1, 2, 3, 4, 5, 6].
We could manually copy each item individually:
let arr1 = [1, 2, 3];let arr2 = [];arr2.push(arr1[0]);arr2.push(arr1[1]);arr2.push(arr1[2]);arr2.push(4);arr2.push(5);arr2.push(6);console.log(arr2); // [1, 2, 3, 4, 5, 6]
Use the unshift method to add items to the beginning of the array:
let arr1 = [1, 2, 3];let arr2 = [4, 5, 6];arr2.unshift(arr1[0], arr1[1], arr1[2]);console.log(arr2); // [1, 2, 3, 4, 5, 6]
Or use the concat method:
let arr1 = [1, 2, 3];let arr2 = [4, 5, 6];arr2 = arr1.concat(arr2);console.log(arr2); // [1, 2, 3, 4, 5, 6]
All these options work, but they make the code lengthy and hardy to read. The spread syntax solves this once you get used to the syntax.
The Spread Syntax
Now using the spread syntax we can write:
let arr1 = [1, 2, 3];let arr2 = [...arr1, 4, 5, 6];console.log(arr2); // [1, 2, 3, 4, 5, 6]
With the spread syntax, we are able to condense the code down to 2 lines. We can also see that arr2 is initialized with the values in arr1, followed by the values 4, 5, 6. This makes it readable as we can see immediately what values will be in arr2.
The Spread Syntax with Objects
You can also use the spread syntax with objects:
let obj1 = {a: 1,b: 2,c: 3,};let obj2 = {...obj1,d: 4,e: 5,f: 6,};console.log(obj2); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
You can also rewrite vaules. We'll change the key of c to have a value of 10.
let obj1 = {a: 1,b: 2,c: 3,};let obj2 = {...obj1,c: 10,d: 4,e: 5,f: 6,};console.log(obj2); // { a: 1, b: 2, c: 10, d: 4, e: 5, f: 6 }
Other Uses
The spread syntax can also be used as function arguments. Without the spread syntax, we would write something like this:
function add(num1, num2) {return num1 + num2;}console.log(add(1, 2));
Using the spread syntax, it would look like this:
function add(num1, num2) {return num1 + num2;}const numbersToAdd = [1, 2];console.log(add(...numbersToAdd));
Although this works, it's probably not ideal in this scenario. When using the spread syntax as part of function arguments, be sure that the number of arguments you pass in match the number of parameters in the function. Otherwise, you may run into unexpected outputs in your program.
Conclusion
JavaScript's spread syntax is a must learn. It is used especially for managing state in front-end libraries and frameworks. Using it, you can quickly copy values from arrays and objects.