How does the spread syntax affect array splice
First of all, Statement A & Statement B will generate different results.
In Statement A
, you are inserting an array (["Lemon", "Kiwi"]
) as an array element at position 2 while removing 0 items. So, you are inserting a string array in another string array at position 2.
var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(2,0,["Lemon", "Kiwi"]);console.log(fruits);
However, Statement B
is much more interesting. To, understand it fully, first log out it's core portion like this:
console.log(...[2,0].concat(["Lemon", "Kiwi"])); // basic array concatenation then spread
As you can see it generates, 2 0 Lemon Kiwi
. Then it is passed as parameter to fruits.splice(..here..)
. According to array#splice
it will enter two strings (Lemon & Kiwi) at position 2, while removing 0 elements.
var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(...[2,0].concat(["Lemon", "Kiwi"]));// is same as fruits.splice(2, 0, 'Lemon', 'Kiwi')console.log(fruits);
NOTE:
array#splice
updates the original array.Statement A
inserts anarray
(IE["Lemon", "Kiwi"]
) in parent string array whereas,Statement B
inserts two strings (IE'Lemon', 'Kiwi'
) in parent string array.
A treats ["Lemon", "Kiwi"]
as one item and inserts it in given index
["Banana", "Orange", ["Lemon", "Kiwi"], "Apple" , "Mango"];
B concats [2,0]
and ["Lemon", "Kiwi"]
and then passes them to splice as comma seperated arguments like
fruits.splice(2,0,"Lemon", "Kiwi");
which modify the array like below
["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]
As per the doc from function signature:
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
In B:
fruits.splice(...[2,0].concat(["Lemon", "Kiwi"]));
Because [2,0].concat(["Lemon", "Kiwi"])
means [2,0,"Lemon", "Kiwi"]
.
So fruits.splice(...[2,0,"Lemon", "Kiwi"]);
becomes fruits.splice(2,0,"Lemon", "Kiwi");
using the spread operator(...
).
Above code you are saying add "Lemon"
, "Kiwi"
, from index 2
witho deleting 0 items.
In this case 2
is start
index, deleteCount
is 0
, and item1
is "Lemon"
, item2
is "Kiwi"
.
Now in A:
fruits.splice(2,0,["Lemon", "Kiwi"]);
You are saying add ["Lemon", "Kiwi"]
, from index 2
with deleting 0 items. In this case 2
is start
index, deleteCount
is 0
, and item1
is ["Lemon", "Kiwi"]
.