How does a spread operator affect array splice

  • A+
Category:Languages

I found the the following code and don't know what the difference between A and B is.

var fruits = ["Banana", "Orange", "Apple", "Mango"]; 

A

fruits.splice(2,0,["Lemon", "Kiwi"]); 

B

fruits.splice(...[2,0].concat(["Lemon", "Kiwi"])); 

 


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 index 3.

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"]));

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 in parent string array whereas, Statement B inserts two strings in parent string array.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: