Saturday, March 4, 2017

Spread and Rest

If we have to combine arrays, spread could come in handy.

const pizzas=["A","B","C"];
const special=["F","G","H"];

If we had to put "D" and "E" between those, we'd have to perform several concat() functions.
With spread, this becomes easy

const combined=[...pizzas,"D","E",...special]; //voila!

Spread takes the elements of an array and separately places those elements where the array was, i.e, inside the container!

Rest is the opposite of spread. While spread unpacks items in a container, rest can pack items into a variable. This can come in handy when we are using the arguments of an array and we want to address only say, the first two arguments first and then deal with the remaining 13 later.

sumJustTwo(12,51,16,27,515);

function sumJustTwo(a,b,...otherNumbers){
console.log("The sum of first two arguments is ",a+b);
}

No comments:

Post a Comment