object.assign() vs spread operator

Corinne Kelly
2 min readApr 30, 2017

--

Spread Operator vs. Object Assign

I came across this discrepancy when learning about “the store” in redux, in which you are never supposed to mutate the state, but instead have to create a new copy of the state object and adjust the copy. The curriculum was teaching us to use the Object.assign method, but I personally love the readability and elegance of the “three dot” spread operator method so I decided to do some research and see what the difference was, if any.

There were a few things that sparked my research.

  1. If Object.assign() can only make new objects, why do i have to declare empty curly brackets “{}” as the first argument every time?
  • The first argument in Object.assign is called the “target” and will MUTATE.

EX:

let target = {first: argument}
let variable = {'Your Mind': 'blown!'}
let newObj = Object.assign(target, variable)
// newObj = {first: argument, 'Your Mind': 'blown!'}
// target = {first: argument, 'Your Mind': 'blown!'}
// variable = {'Your Mind': 'blown!'}

That is why in Redux we always want to use an empty Object (“{}”) as the first argument, since we are trying to make a new copy and do not want to mutate the current state object.

2. Why does everyone keep using the term “verbose”?

VERBOSE: Containing more words than necessary

Javascript is not the only language I am continuously learning but that is exactly how I would describe the Object.assign() function if I’m trying to make a copy of an object.

Ironically, the official javascript MDN docs use the “spread operator syntax” (aka the three dots) to describe what Object.assign does. If that doesn’t prove how much more readable the spread operator is I don’t know what will.

Syntax description of Object.assign in MDN docs

Some ex:

Cloning an object:

var obj = { “Who’s better?” : “TBD” }
Object.assign({}, obj)
{…obj}

Object.assign is definitely verbose here.

Cloning an array:

var arr = [“this”, “one”, “is”, “obvious”]
Object.assign([], arr)
// ERR Oh no! Did you try to put an array in me? I can only copy objects! -Object.assign()
[..arr]
//don’t worry I got this -Spread Operator

That’s 2–1 spread operator.

--

--