We have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:
const a = 'foo';
const b = 42;
const c = {};
const o = {
a: a,
b: b,
c: c,
};
There is a shorter notation available to achieve the same:
const a = 'foo';
const b = 42;
const c = {};
const o = { a, b, c };
console.log(o.a === { a }.a);
Duplicate property names
When using the same name for your properties, the second property will overwrite the first.
const a = { x: 1, x: 2 };
console.log(a);
In ECMAScript 5 strict mode code, duplicate property names were considered a SyntaxError
. With the introduction of computed property names making duplication possible at runtime, ECMAScript 2015 has removed this restriction.
function haveES2015DuplicatePropertySemantics() {
'use strict';
try {
({ prop: 1, prop: 2 });
return true;
} catch (e) {
return false;
}
}