DEV Community

Esto Triramdani N
Esto Triramdani N

Posted on

Spread Operator

Spread Operator

Let’s go to the use cases!

Spreading an Array

In a case, we want duplicate an array. We can’t copy just like this.

const arr = [1, 4, 2];
const arr2 = arr; 
Enter fullscreen mode Exit fullscreen mode

If we do that, when we manipulate arr the arr2 will be affected.

arr.push(100);
console.log(arr); // [1, 4, 2, 100]
console.log(arr2); // [1, 4, 2, 100]
Enter fullscreen mode Exit fullscreen mode

Output what we want is

console.log(arr); // [1, 4, 2, 100]
console.log(arr2); // [1, 4, 2] => we don't even touch `arr2` so it should be the same
Enter fullscreen mode Exit fullscreen mode

This case happens because we pass by reference to arr2. Simply, we don’t really have arr2. We may call arr2 just an alias of arr.

To completely copy arr to arr2 we can use something called spread operator.

Spread operator is three dots ... operator.

Before we copy arr, if we do console.log(...arr) the output will be

1 4 2
Enter fullscreen mode Exit fullscreen mode

It means we now have 3 values that is not belong to any variables or constants. So we can do this to copy an array.

const arr = [1, 4, 2];
const arr2 = [ ...arr];
// arr = [1, 4, 2] 
Enter fullscreen mode Exit fullscreen mode

If we push stuff to arr, arr2 will stay the same.

arr.push(50);
console.log(arr); // [1, 4, 2, 50]
console.log(arr2); // [1, 4, 2]
Enter fullscreen mode Exit fullscreen mode

Spread operator can be used to combine multiple arrays.

const newArr = [...arr1, ...arr2, ...arr3, ...arr4];
Enter fullscreen mode Exit fullscreen mode

Spreading an Object

Spread operator can also implemented to an object.

Let’s say we have two objects.

const personProfile = {
    name: 'Esto',
    age: 22,
}; 
const personHobbies = {
    indoor: ['Reading', 'Sleeping', 'Coding'],
    outdoor: ['Football', 'Running']
}
Enter fullscreen mode Exit fullscreen mode

We can combine two object with this code.

const person = { ...personProfile, ...personHobbies };
Enter fullscreen mode Exit fullscreen mode

Or we can copy personProfile to personProfileBackup.

const personProfileBackup = { ...personProfile };
Enter fullscreen mode Exit fullscreen mode

Conclusion

The best case to copy an object or an array is when our app have “Customize” feature.

When user customize their theme, that customized configuration stored in a new object without replacing the old one.

If user click reset, we can replace modified object with the old one. Of course, we will find other use cases if we started building real world project!

See you!

Top comments (0)