How do I check if an object has a key in JavaScript? [duplicate]

Asked 2023-09-21 08:08:20 View 331,042

Which is the right thing to do?

if (myObj['key'] == undefined)

or

if (myObj['key'] == null)

or

if (myObj['key'])
  • Relevant benchmarks: jsperf.com/checking-if-a-key-exists-in-a-javascript-array - anyone
  • You can try !!myObj.key which returns true (if in) and false (if not). - anyone
  • @Anh-ThiDINH be careful, this doesn't work with boolean values. const user = { name: "John", admin: false }; !!user.name will return true. But !!user.admin will return false even though the 'admin' key exists - anyone
  • now best would be myObj?.key - anyone
  • I'm vote #1700 on your duplicate question :) Well done. - anyone

Answers

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

Answered   2023-09-21 08:08:20

  • The reason 'in' is considered not good is because it searches the whole prototype chain. - anyone
  • and even better - if(myObj && 'key' in myObj) - anyone
  • what is wrong with searching the whole prototype chain (unless you know you don't want to for some reason)? - anyone
  • @reconbot, in normal OO languages you often invoke methods defined in parent classes. What is wrong doing the same thing in js? Does it imply js prototype chains themselves are bad? Some people might actually use them. - anyone
  • could have done like this Object.keys(ObjectInWhichYouwantTocheckTheKey).includes('keyInObject') :) cheers - anyone

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

Answered   2023-09-21 08:08:20

  • one problem i found with hasOwnProperty in firefox is it will return false for inherited key - anyone
  • @maldy: isn't that the whole point of has**Own**Property ? - anyone
  • ESLint rejects this as Do not access Object.prototype method 'hasOwnProperty' from target object. - anyone
  • @CJBrew it might be because you have the eslint flag no-prototype-builtins in which case you can still use it by doing {}.hasOwnProperty.call(object, "key") - anyone
  • I'm gonna leaves this here for anyone that will wonder why ESLint is complaining eslint.org/docs/rules/no-prototype-builtins - anyone