0
Q:

how to check if object has key javascript

myObj.hasOwnProperty('key') // it checks object for particular key and not on prototype   
8
!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"
1
"key" in obj // true, regardless of the actual value
0
var obj = { key: undefined };
obj["key"] !== undefined // false, but the key exists!
0
"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:
!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:
obj.hasOwnProperty("key") // true
0

New to Communities?

Join the community