Apart from that it’s cloning so changing the clone will not change the initial array (note it’s only a shallow clone though!*), it’s really helpful for mixing two arrays. The syntax is also short and clear. When you’re doing this hundreds of times, it can really make the code cleaner.
let arr1 = ["a", "b", "c"]
let arr2 = ["1", "2", "3"]
let mix = [...arr1, ...arr2] // ["a", "b", "c", "1" ,"2", "3"]
or even better with objects, because with objects, duplicate properties are not duplicated, the last duplicate is the value. So say you have some default settings:
let defaults = {
setting1: false,
setting2: false,
}
You can mix in the state the user changed:
let change = {
setting1: true
}
let settings_state = {
...defaults,
...change // last duplicate property determines value
}
// will give you:
// settings_state = {
// setting1: true,
// setting2: false,
// }
This can all also be used to pass an arbitrary amount of values in function calls.
* Regarding the shallow cloning. Anytime you do value = somevariable
and that variable is an object or an array you are just creating a reference. You are not copying the values. Same thing with spread (it only loops and assigns one level deep). When you spread an array of objects, it’s only a shallow copy. So if you spread [object, object2, object3]
you’re only copying the array and the references to the objects, but not the objects themselves. Note, you can nest spreads, but it’s better to have a function for deep cloning.