Home > Net >  Should I use the in operator or property accessors to check if a key exists in an object?
Should I use the in operator or property accessors to check if a key exists in an object?

Time:09-02

What would be the pros/cons of using:

if ('key' in obj)

vs

if (obj['key'])

Is one faster than another?

CodePudding user response:

For the question in title, you must use the first form, because that's the only correct way of checking if a key exists in an object.

Consider:

const x = {
  a: 1,
  b: undefined,
  c: 0
}

The keys a, b and c exist in x. Only the first form of your question will correctly give true for the three cases.

CodePudding user response:

Consider the following:

const myObj = {
  hello: undefined,
};

console.log(myObj.hello);
console.log('hello' in myObj);

The key "hello" is defined in myObj but its value is undefined. If you truly only need to know if the key exists, regardless of what it contains, the in syntax is what you want-- if you need to know if the value contained is falsy or not then you'll want to access actual the value using the dot-operator or square brackets.

Regarding speed-- unless you are doing this with some extremely great frequency, I suspect that fumfering over the speed difference here is premature optimization at best. If for some reason you expect this operation to be happening thousands or millions of times, then perhaps you might consider leveraging some library that puts an emphasis on optimization, such as lodash's has() method.

Finally, one last thing worth mentioning-- both of these methods will search not only the object itself but also its prototypes. If this is not desirable, you might consider using .hasOwnProperty() as an alternative:

const myObj = {
  hello: undefined,
};

console.log(myObj.hasOwnProperty('hello'));
console.log(myObj.hasOwnProperty('toString'));

  • Related