Checking if a key exists in a JavaScript object?
Explanation
Here we will check if a key exists in a JavaScript object. But we do not have an accurate way of testing whether a key exists. So we will check if the value of the key is defined or not. For that we will use :
var obj = { key: undefined };
console.log(obj["key"] !== undefined); // false, but the key exists!
Instead, you should use the operator in
:
var obj = { key: undefined };
console.log("key" in obj); // true, regardless of the actual value
And if you want to check if a key does not exist, So you have to remember that you have to use parenthesis:
var obj = { not_key: undefined };
console.log(!("key" in obj)); // true if "key" doesn't exist in object
console.log(!"key" in obj); // Do not do this! It is equivalent to "false in obj"
Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty
:
var obj = { key: undefined };
console.log(obj.hasOwnProperty("key")); // true