EN
JavaScript - check if key exists in object
0
points
In this article, we would like to show you how to check if key exists in object working with JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var object = { keyName: 'A'};
console.log('keyName' in object); // true
Practical example
In this example, we use for...in
statement to check if a key exists in the object. This way true
value is returned even when the key value is undefined
.
// ONLINE-RUNNER:browser;
var object = { keyName1: 'A', keyName2: undefined };
console.log('keyName1' in object); // true
console.log('keyName2' in object); // true (key exists but value is undefined)
console.log('keyName3' in object); // false
Alternative solution
You can also use hasOwnProperty()
method to achieve the same result as above.
// ONLINE-RUNNER:browser;
var object = { keyName1: 'A', keyName2: undefined };
console.log(object.hasOwnProperty('keyName1')); // true
console.log(object.hasOwnProperty('keyName2')); // true
console.log(object.hasOwnProperty('keyName3')); // false