I was trying to understand what is the difference between spread syntax vs slice method in the following approach.
suppose I want to make an actual copy of an array,
Those two methods aren’t actually equivalent though. Slice is a function on Array.prototype
and is aware of the array’s implementation. It will create a very efficient deep copy. More importantly though, .slice()
will preserve the sparseness information of your array.
In contrast, [...Array]
will simply create a new array from an iterable view of your existing array. Not necessarily as efficient.
Try this:
var a = [];
a.length = 3;
console.log("slice:", a.slice());
console.log("spread:", [...a]);
With Chrome Browser developer console, I get these results:
slice: (3) [empty × 3]
spread: (3) [undefined, undefined, undefined]
If your array is particularly huge+sparse, array.slice()
will be exceptionally fast. [...array]
will probably hang your browser.