spread operator

ref – https://codeburst.io/javascript-the-spread-operator-a867a71668ca

The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected

Doing things in immutable way:

Say you have an object

You want to update it (add a property). Keep everything immutable.
So you’d create another literal object just like meal and add your property.

But this is a lot of typing and too much work if it has many properties.

In order to remedy this, we’d use the spread operator.

Now, let’s say we want to use it.

This is rather tedious and too wordy.
Let’s use Destructuring to get what we need.

How to remove or delete field. Let’s delete id by using rest syntax.

Now mealWithoutId will have all properties of updatedMeal, without the id.

now updatedMeals will have the third meal.

But say we want to update lunch?

array.map(fn) returns a new new array with the updated changes

Use Array.filter to remove items from array immutably.

Various Usages

given…normally, the middle reference in arr would reference var middle. This makes it so that its an array inside of an array. Its not what we want.

What we can do is to expand middle’s elements into arr like so:

Remember the spread operator definition you just read above? Here’s where it comes into play. As you can see, when we create the arr array and use the spread operator on the middle array, instead of just being inserted, the middle array expands. Each element in the middle array is inserted into the arr array. This means that instead of nested arrays, we are left with a simple array of numbers ranging from 1 to 6.

Copying arrays

Voila! We have a copied array. The array values in arr expanded to become individual letters which were then assigned to arr2. We can now change the arr2 array as much as we’d like with no consequences on the original arr array.

Appending Arrays

String to Array

Bonus example: Use the spread operator to simply convert a string to an array of characters

No need to use ‘call’