The spread operator is one feature of JavaScript which I often overlook. This week, I wanted to take a deeper look into spread syntax and write a short summary of the benefits.
First, and probably the most common use of the spread operator, shallow-cloning. Sure, we can get a shallow copy of an array from the slice method, but the spread syntax looks a little cleaner to me.
let arr1 = [1, 2, 3];
// slice
let arr2 = arr1.slice();
// spread
let arr3 = [ ...arr1 ];
// arr2 value: [1, 2, 3]
// arr3 value: [1, 2, 3]
We can also use the spread operator to get a shallow copy of an object.
let obj1 = { v1: 0, v2: 1 };
let obj2 = { ...obj1 };
// obj2 value: { v1: 0, v2: 1 }
Another great use of the spread operator, array concatenation.
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
// concat
let arr3 = arr1.concat(arr2);
// spread
let arr4 = [ ...arr1, ...arr2 ];
// arr3 value: [1, 2, 3, 4, 5, 6]
// arr4 value: [1, 2, 3, 4, 5, 6]
You're able to merge objects this way as well.
let obj1 = { v1: 0, v2: 1, v3: 2 };
let obj2 = { v2: 10, v3: 20 };
let obj3 = { ...obj1, ...obj2 };
// obj3 value: { v1: 0, v2: 10, v3: 20 }
It's also possible to pass multiple arguments to a function or method, using the spread operator.
const add = (a, b) => {
return a + b;
}
let args = [10, 11];
let result = add( ...args );
// result value: 21
I do think that spread syntax can help to improve the cleanliness of our code. If you know of any other neat tricks or tips, please leave a comment below.
Top comments (0)