Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  42] [ 3]  / answers: 1 / hits: 16546  / 6 Years ago, tue, july 3, 2018, 12:00:00

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, I can probably easily do it using spread syntax



var fruits = [Banana, Chips , Orange, Lemon, Apple, Mango]
var newCitrus = [...fruits]


If I console.log this



[Banana, Chips, Orange, Lemon, Apple, Mango] 


but I can also create a copy of an array using the slice method. Considering the same array above, if I do something like this...



var citrus = fruits.slice(0);


and then console log it, it will give me exactly the same array which I would've got through spread syntax



[Banana, Chips, Orange, Lemon, Apple, Mango] 


Since both of them takes about the same time to code/write, What is the difference here? which approach should I usually choose?


More From » slice

 Answers
10

Performance aside slice is just a function on Array.prototype so it will work only for arrays. Spread syntax on the other hand will work for any iterable (object which satisfy iterable protocol) so it will work out of the box on any String, Array, TypedArray, Map and Set. You can also easily create custom iterables.


There is also a difference when it comes to sliceing and spreading arrays with holes (sparse arrays). As you can see below, slice will preserve sparseness while spread will fill holes with undefined.


Array(3)         // produces sparse array: [empty × 3]
Array(3).slice() // produces [empty × 3]
[...Array(3)] // produces [undefined, undefined, undefined]

Spread syntax can also be used to make shallow clones of objects:


const obj = { foo: 'bar', baz: 42 };
const clone = { ...obj };
obj.foo === clone.foo // true
obj.baz === clone.baz // true
obj === clone // false (references are different)

[#54059] Saturday, June 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skylerselenem

Total Points: 282
Total Questions: 101
Total Answers: 107

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;