In this post, we will learn how to check if a key exists in an object in JavaScript using multiple ways.
1. Using the in Operator
The in
operator is a convenient way to check if a key exists in JavaScript objects.
It returns a boolean value, true
if the key exists; otherwise false
.
You must specify the key
as a string to the left side and an object on the right side of the in operator. For Example 'key' in Object
.
const book = {
title: 'The Lord of the Rings',
};
console.log('title' in book); // 👉️ returns true
console.log('price' in book); // 👉️ returns false
if ('title' in book) {
// 👇️ this runs
console.log('key exists in object');
}
If you want to check if the key does not exist in an object, add the exclamation mark (!
) at the beginning and wrap the expression in parenthesis.
const book = {
title: 'The Lord of the Rings',
};
console.log(!('title' in book)); // 👉️ returns false
console.log(!('price' in book)); // 👉️ returns true
if (!('price' in book)) {
// 👇️ this runs
console.log('key does not exists in object');
}
Wrapping the expression in parenthesis allows to evaluate it as a whole.
2. Using the hasOwnProperty() Method
The hasOwnProperty()
method is another way to check if a key exists in an object in JavaScript.
It returns a boolean value true
if the key exists, and if the property is inherited or does not exist, it returns false
.
const book = {
title: 'The Lord of the Rings',
};
console.log(Object.hasOwnProperty('title')); // 👉️ returns true
console.log(Object.hasOwnProperty('price')); // 👉️ returns false
if (Object.hasOwnProperty('title')) {
// 👇️ the key 'title' exists, but this never runs
console.log('key exists in object');
}
Difference between the in operator and hasOwnProperty() method
Looks like in
and hasOwnProperty()
works the same way, but there is a significant difference between them.
The in
operator checks the key in the object and its prototype chain, while the hasOwnProperty()
method only checks for key existance directly on the object.
3. Using the Optional Chaining(?.) Operator
The Optional Chaining(?.
) Operator is another alternative to check if the key exists in the object.
It returns the key value if it exists; otherwise, undefined
.
const book = {
title: 'The Lord of the Rings',
};
console.log(book?.title); // 👉️ returns 'The Lord of the Rings'
console.log(book?.price); // 👉️ returns undefined
if (book?.title !== undefined) {
// 👇️ this runs
console.log('key exists in object');
}
We used optional chaining to check whether the title
and price
keys exist in the book
object.
Since title
exists on the book
object, book?.title
evaluates to The Lord of The Rings
, and the price
key does not, undefined
is returned for book?.price
.
⚠️ The conditional check will not work for keys with undefined
value in the object.
const book = {
title: undefined,
};
console.log(book?.title); // 👉️ returns undefined
if (book?.title !== undefined) {
// the key 'title' exists, but this never runs
}
The book
object has the key title
, but the if
statement does not run if the value is set to undefined
.
Conclusion
We can check if a key exists in an object in JavaScript using multiple ways, but each works differently, so you can choose one per your requirements.
Learn More:
- SyntaxError cannot use import statement outside a module in JS
- Pad a Number with Leading Zeros in JavaScript
- Unexpected identifier Error in JavaScript
- Dynamically Access Object Property Using Variable in JavaScript
- Replace All String Occurrences in JavaScript
- Get the Last N Elements of an Array in JavaScript
- Calculate Percentage Between Two Numbers in JavaScript
- Remove Special Characters from a String in JavaScript
- Using async/await with a forEach loop
- Wait for all promises to resolve in JavaScript