How code is written today

INPUT · Slides

Spreading things out

01 / 06

You want more without changing the original

To add an item to an array you have used push. But push rewrites the original array itself.

That is trouble when you want to use the original data later. Wanting both "before adding" and "after adding" happens more often than you would think.

const fruits = ["apple", "orange"];fruits.push("peach");console.log(fruits);

Result

["apple", "orange", "peach"]

02 / 06

Spread the contents with ...

Write ..., three dots, in front of an array and it lines the contents out loose, there and then. This way of writing is called spread.

[...fruits, "peach"] means "an array with all of fruits' contents lined up, and "peach" added behind them".

const fruits = ["apple", "orange"];const added = [...fruits, "peach"];console.log(added);

Result

["apple", "orange", "peach"]

03 / 06

The original stays as it was

This is the most important part. What you made is a new array, and the original array has not changed at all.

Since the original is not rewritten, the accident of "I looked at the original data later and it had changed" cannot happen. The same thinking as map and filter returning new arrays.

const fruits = ["apple", "orange"];const added = [...fruits, "peach"];console.log(fruits);console.log(added);

Result

["apple", "orange"]
["apple", "orange", "peach"]

04 / 06

Join two arrays

You can write as many ... as you like. Line them up and you can build one array joining two arrays.

No more running a for and pushing into one of them. What you want becomes one line, just as it is.

const spring = ["cherry blossom", "dandelion"];const summer = ["sunflower"];const flowers = [...spring, ...summer];console.log(flowers);

Result

["cherry blossom", "dandelion", "sunflower"]

05 / 06

It works on objects too

Write ... inside { } and you can spread out all of an object's entries.

Write the same name after the spread and it gets overwritten by that one. It is the standard shape for "make an object with just one entry different".

const user = {  name: "Yui",  age: 20,};const next = { ...user, age: 21 };console.log(user);console.log(next);

Result

{ name: "Yui", age: 20 }
{ name: "Yui", age: 21 }

06 / 06

Let us check it all together

Tidying up what we have so far.

  • ... spreads the contents out on the spot
  • what you get is a new array or object; the original does not change
  • you can line up as many as you like, so joining and adding are written the same way

Right — let us spread some things out.