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

What would be the pros/cons of using:

if ('key' in obj)


if (obj['key'])

Is one faster than another?

>Solution :

Consider the following:

const myObj = {
  hello: undefined,

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,


Leave a Reply