Let's consider a JS object,
const author = { name: 'Param', age: 31 };
Now, let's check whether a key name
exists in the object or not using the in
operator.
if ('name' in author) { console.log('`name` key found in author object'); } if (!('website' in author)) { console.log('`website` key not found in author object'); }
There is another object method hasOwnProperty
to check whether key present,
console.log(author.hasOwnProperty('name')); // true console.log(author.hasOwnProperty('website')); // false
The only difference between in
and hasOwnProperty
are,
hasOwnProperty
works only on the user-defined object properties. It won't work on the inherited properties from parent objects.in
works for all keys whether it is defined or inherited from parent objects
This technique only works for the direct keys, it won't work for nested keys.
We will see a separate example to check whether the object key exists in any level of the nested object.