Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the spread syntax affect array splice

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

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

A

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

B

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

var fruits = ["Banana", "Orange", "Apple", "Mango"];  var A = fruits.splice(2, 0, ["Lemon", "Kiwi"]);  var B = fruits.splice(...[2, 0].concat(["Lemon", "Kiwi"]));    console.log(A)  console.log(B)
like image 305
vuvu Avatar asked Jul 11 '18 13:07

vuvu


People also ask

What does spread operator do to an array?

The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.

What does spread syntax do?

Spread syntax ( ... ) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

Does splice affect the array?

2. The splice() method changes the original array and slice() method doesn't change the original array.

What happens when you use spread on object?

Spread syntax (also known as the Spread Operator) is used to copy the enumerable properties of an object to create a clone of it. We can also update an object or merge with another object using the spread syntax.


Video Answer


1 Answers

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.
like image 52
BlackBeard Avatar answered Sep 28 '22 00:09

BlackBeard