0

In the redux docs on immutable update patterns I've noticed they said that you can update objects by using the spread operator and then overwriting a property.

Is there something special about the object spread operator? If not, then why can you overwrite a property in the definition of an object literal (like in the code below) without mutating data?

const a = {
  foo: 'bar',
  foo: 'bla'
}
Gwater17
  • 2,018
  • 2
  • 19
  • 38
  • It's not clear how `...` spread syntax is relevant to the object literal syntax that accepts multiple similar keys. – zerkms Aug 29 '17 at 01:40
  • "why can you overwrite" --- because the standard allows that. – zerkms Aug 29 '17 at 01:40
  • Having an object with duplicate keys is a mistake that your linter should catch. (This doesn't even work in older browsers, they only allowed this as of ES6 because they didn't know how deal with computed properties otherwise). – Bergi Aug 29 '17 at 03:02
  • "*you can update objects by using the spread operator*" - No! The spread syntax is part of an object literal, which *creates a new object*. – Bergi Aug 29 '17 at 03:03
  • @Bergi https://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5 was it actually forbidden before es2015? – zerkms Aug 29 '17 at 10:01
  • @zerkms Yes: "*If previous is not undefined then throw a SyntaxError exception …*" from that section. See also [this question](https://stackoverflow.com/q/30617139/1048572) – Bergi Aug 29 '17 at 10:05
  • @Bergi yep, I suspected the section you referred to but am not qualified enough to understand all the internal properties they access there. Thanks. – zerkms Aug 29 '17 at 10:09

1 Answers1

3

In object literals we can use the spread operator (...) it inserts properties from a given object, to the object literal... so if you have:

const a = {
  foo: 'bar',
  test: 'test'
}

A new object can be created using the spread operator in the object literal definition..

const b = {
   ...a, //spread operator that introduces object properties
   foo:'bla'
}

The b object would be

{ foo: 'bla', test: 'test' }

Take in to account that the if two properties have the same name, the order will define which one takes priority and indeed we can overwrite a property definition in the object literal.

if the definition was:

const b = {
   foo:'bla',
   ...a, //the spread operator is defined at the end
}

The b object will be:

{foo: "bar", test: "test"}

Refer to this article

Note: This is a ES2018 proposal, currently working in chrome..

Community
  • 1
  • 1
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37