Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

vs

if (obj['key'])

Is one faster than another?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading