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)
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.
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.
2. The splice() method changes the original array and slice() method doesn't change the original array.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With