Last updated on May 26, 2021 by Suraj Sharma
In this tutorial, you’ll learn 2 ways to check if a key or property exists in given JavaScript object.
in
operatorYou can use the in
operator in javascript to check if a key exists in a given object.
const obj = {
a: 1,
b: 2
};
console.log('a' in obj); // true
console.log('c' in obj); // false
The in
operator returns true
if the key to the left of it is present in the object right to it in the expression, otherwise it returns false
.
'key' in object
The Object.hasOwnProperty()
method can be used to check the immediate property of the object, i.e. the property not inherited from its parent object.
The hasOwnProperty
method always returns a boolean value.
const obj = {
a: 1,
b: 2
};
console.log(obj.hasOwnProperty('c')) // false
console.log(obj.hasOwnProperty('b')) // true
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.