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 an array (IE ["Lemon", "Kiwi"]) in parent string array whereas, Statement B inserts two strings (IE 'Lemon', 'Kiwi') in parent string array.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)