ES2015 const and object expansion

So i’ve been fighting with this problem this morning. I’m relatively new to ES2015 and still learning a lot of things regarding the very nice constructs you can use in there.

One that threw me off this morning is this:

export const someDefaultReduxStateObject = {
    property1: null,
    property2: []
}

myArray = []
myArray.push({...someDefaultReduxStateObject})
myArray.push({...someDefaultReduxStateObject})

Now you would expect that this simple piece of code would just create 2 objects that are completely different but sadly no, at least, not entirely.

The two objects will be a copy of “someDefaultReduxStateObject” but the property2 will be shared between the two. If you:

myArray[0].property2.push({newObject: 2})

You will end up with the new object in both instances. To this end, you either have to override the const in object spread like so:

myArray.push({...someDefaultReduxStateObject, property2: []})
myArray.push({...someDefaultReduxStateObject, property2: []})

Or create a function instead that would return a completely independent copy each time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.