This page looks best with JavaScript enabled

Careful with key names of an object in Javascript

 ·   ·  ☕ 1 min read

An object’s key can be anything - even a reserved keyword. And, this may cause unexpected problems in some script engines.

Consider -

1
2
3
4
5
const operations = {
  add: "add something",
  delete: "remove something",
  prototype: "do something"
};

operations is valid. And, you can go ahead and use the props in any way you wish. We are using node to execute the script.

1
2
3
console.log(operations.add); // add something
console.log(operations.delete);
console.log(operations.prototype); // do something

Turns out, nothing really happens even if you try to confuse the engine.

1
2
operations.prototype.noop = "nothing";
console.log(operations.prototype); // do something

But the results may not be the same across browsers - especially on older engines. It can lead to runtime syntax errors that are hard to debug and frustrating for everyone.

So -

  • never use special words in your keys
  • if you must use such keys, enclose them using quotes and use bracket notation to refer to them
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things