HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyobjecthowhascheckjavascript

Problem

Which is the right thing to do?

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


or

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


or

if (myObj['key'])

Solution

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.

Code Snippets

if ('key' in myObj)
if (!('key' in myObj))
myObj.hasOwnProperty('key')

Context

Stack Overflow Q#455338, score: 3508

Revisions (0)

No revisions yet.