How to check if a property exists in a JavaScript object
Last updated: October 13, 2022.
Before accessing an object property, it is often a good idea to check whether it exists first so that result-handling can kick in if the result is negative.
Since every property in an object must have its own unique key, you can check for the existence of a property key value.
For this, a method exists on JavaScript objects called hasOwnProperty()
. It accepts a key value and when called searches the properties of the object on which it is called for the key value entered, returning Boolean true or false:
const obj = {
singer: "Simon",
singer2: "Garfunkel",
};
obj.hasOwnProperty('singer'); // true
obj.hasOwnProperty('singer2'); // true
obj.hasOwnProperty('singer3'); // false
// Checks main object
console.log(obj.hasOwnProperty('toString')); // false
console.log(obj.hasOwnProperty('hasOwnProperty')); // false
// But does not check properties on its prototype
But, as you can see in the example, hasOwnProperty
does not check an object's prototype for the existence of a property.
So if you want to check the main object and its prototype, you need to use another approach.
Thankfully, for this you can use the in
operator, using property in object
syntax:
const obj = {
singer: "Simon",
singer2: "Garfunkel",
};
'singer' in obj; // true
'singer2' in obj; // true
'singer3' in obj; // false
// Checks main object...
'toString' in obj; // true
'hasOwnProperty' in obj; // true
// ...and methods on its prototype!