Open In App

How to check a key exists in JavaScript object ?

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 if a key exist in given object

check a key exists in JavaScript object

Lets create a JavaScript object having with given key-values and then we will apply 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. 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);


Output

false
true

2. 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);


Output

false
true


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads