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?
This will console.log
Huh? No, it won't. Why is that different from thefruits
? Also, you're not usingsplice
anywhere in your code – CertainPerformance Jul 3 '18 at 23:54slice
allows for more control which part of the array to take, whereas the spread operator allows for quick "pasting" into arrays, e.g.["other", "elements", ...fruits]
. – ASDFGerte Jul 3 '18 at 23:58[...arr].slice()
to satisfy all users – Mark M Jul 4 '18 at 0:01[].concat([...arr].slice())
– Jaromanda X Jul 4 '18 at 0:03