How Do Object.assign and Spread Actually Work?

Yazeed Bzadough
8 min readDec 17, 2017

The code in my last article made good use of spread because of its powerful expressivity. Let’s break it down to better appreciate its magic.

What is spread?

It lets you expand any iterable (like an array or string) in an array or function parameters, or expand any object into another object.

By now, we’ve seen plenty of spread examples (React, Redux, etc)

Combining arrays with spread
Combining objects with spread

Let’s dive deeper into each one.

We’ll create a function called identity that just returns whatever parameter we give it.

identity = (arg) => arg

And a simple array.

arr = [1, 2, 3]

If you call identity with arr, we know what’ll happen

But what if you spread (can I use it as a verb?) arr into identity?

Wait, where’s 2 and 3? identity’s holding out on us!

Mmm, probably not. Something else is going on here. Let’s use my favorite tool for analyzing next-gen JavaScript code: the Babel REPL.

--

--