How to check a key exists in JavaScript object ?
Last Updated :
17 Apr, 2024
In this article, we will learn how to check if a key exists in JavaScript object, with help of various examples.
Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. Here, we have an object and we need to check whether the given key is present in the given object or not.
check a key exists in JavaScript object
Lets create a JavaScript object having with given key-values and then we will explore different approaches to check a key exist in the Object.
Javascript
// Given object
let exampleObj = {
id: 1,
remarks: 'Good'
}
Examples of checking if key exist in JavaScript Object
1. Check if Key Exists in Object Using in operator
The in operator returns a boolean value if the specified property is in the object.Â
Syntax:
'key' in object
Example: This example uses the “in” operator to check the existence of a key in a JavaScript object.Â
Javascript
let exampleObj = {
id: 1,
remarks: 'Good'
}
// Check for the keys
let output1 = 'name' in exampleObj;
let output2 = 'remarks' in exampleObj;
console.log(output1);
console.log(output2);
2. Check if Key Exists in Object Using hasOwnProperty() method
The hasOwnProperty() method returns a boolean value that indicates whether the object has the specified property. The required key name could be passed in this function to check if it exists in the object.Â
Syntax:
object.hasOwnProperty('key')
Example: This example uses hasOwnProperty() method to check the existence of a key in a JavaScript object.Â
Javascript
let exampleObj = {
id: 1,
remarks: 'Good'
}
// Check for the keys
let output1 = exampleObj.hasOwnProperty('name');
let output2 = exampleObj.hasOwnProperty('remarks');
console.log(output1);
console.log(output2);
Share your thoughts in the comments
Please Login to comment...