Understanding the Spread Operator in JavaScript

Marina Mosti on February 26, 2019

{...object} The first time I looked at this I was really confused about what it was supposed to mean, or even do, but harnessing the power of the ... [Read Full]
markdown guide

Good article! However, I feel like it's important to mention that the spread operator does not perform a deep clone on objects, but rather a shallow copy. This means that the spread operator will copy simple values (such as integers, strings and such) but keep the same references for objects. For example:

const obj = { a: 1, b: { a: 1 } };
const copy = {...obj}
copy.b.a = 2


This prints 2 and 2 because the property b was shallow copied, which makes copy.b point to the exact same object as obj.b.


Hey Fran, thanks for the addendum. I actually should have probably put a little more clarity on this part, but i've made a small correction and your example is also super clear


Great intro to spread! Looks super useful for making copies. Though at the end, I believe you mean to say

original.child == copy.child


original.child == original.copy

) is that right?


🤦‍♀️This is why you dont hotfix posts while doing 3 other things. Thanks! :)

const randoms = function*(x){while(true)yield Math.random()*x|0}
const [a, b, c] = randoms (1000)
console.log(a, b, c)

open eye crying laughing emoji


I love spread operator it has saved me lot of times.. instead of using Array.prototype.slice..
Because I always mix it up with Array.prototype.splice...


Does it seems like in Python? that

func(1, 2, a=1, b=2)

def func(args, **kwargs):
print(*args) --> [1, 2]
*kwargs) --> {a: 1, b: 2}


Really great explanation of this! Especially like that you gave the example of copying an object in that way. That's a super important use case.


You're right, it's very simple and super useful :)


Nice article. Would you mind mentioning that the copy with the spread operator creates a shallow copy of the object and not a deep one.


Hey Birju, you're right. I try to keep these as simple as possible and sometimes overlook some of the more advanced concepts in favor of clarity. Will make a note, thanks


I always preferred the term 'splat' operator. It sounds so much cooler. Nice article, thanks!

code of conduct - report abuse