1

This is a question about Javascript(and possibly other languages) fundamentals. I was developing a project and at some point a realized I had defined the same key more than once in an object but no error appeared on console. After some research I couldn't find a clear/official statement to what happens in this situation or how this affects the program. All I could find out is the output in a simple example:

let obj = {key1:1, key1:2, key1:3};

console.log(obj.key1);// >> output = 3
console.log(Object.keys(obj));// >> output = ['key1']

My question is: The value is just redefined and all previous declarations are erased? Is this a limitation or some kind of error of Javascript?

Marcus Castanho
  • 145
  • 1
  • 3
  • 9
  • 1
    Yes, no. Strictly, properties aren't declared, they're created during assignment or by various methods, e.g. [*Object.defineProperty*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). In [strict mode](https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it/1335881#1335881), attempting to create duplicate properties throws a syntax error. – RobG Mar 11 '21 at 23:25

1 Answers1

2

The value is just redefined and all previous declarations are erased?

Yes. When an object literal contains duplicate keys, only the final key in the object literal will exist on the object after the object is evaluated.

Is this a limitation or some kind of error of Javascript?

It's permitted, but it's nonsense. Like lots of things in programming, there are things which are syntactically allowed but don't make any sense in code.

But you can use a linter to prevent from making these sorts of mistakes, eg ESLint's no-dupe-keys.

There's one case where something very similar to duplicate keys can be common, which is when using object spread, eg:

const obj = { foo: 'foo', bar: 'bar' };
// Now say we want to create a new object containing the properties of `obj`
// plus an updated value for `foo`:
const newObj = { ...obj, foo: 'newFoo' }

This sort of approach is very common when working with data structures immutably, like in React. It's not exactly the same thing as an outright duplicate key in the source code, but it's interpreted the same way - whatever value gets interpreted last in the key-value list (regardless of if the key is spread or static) will be the value that the final object contains at that key.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320