Check if a key exists in an object in JavaScript
In this tutorial, we will see how to check if a key exists in an object in JavaScript. We will use hasOwnProperty()
method and in
operator to check if a key or property exists in an object.
Using hasOwnProperty() method
This is an object prototype method. This method lets us determine whether an object owns a specific property. This method returns a boolean value indicating whether the specified property exists in the object.
Here is the JavaScript program below to check if a key or property exists in an object Using hasOwnProperty()
method.
// Create an Object const obj = { key1: 'Value1', key2: "value2", key3: 25 }; // Check If 'key1' is exist in that Object if (obj.hasOwnProperty('key1')) { console.log("The key exists in the object"); } else { console.log("The key does not exists in the object"); }
In the above program, the hasOwnProperty()
method will check if the object obj
has a property with the key “key1“. If the specified key is present in the object the hasOwnProperty()
method will return true and the code inside the if
block will execute.
Otherwise, it will return false and the code inside the else
block will execute.
Output:
The key exists in the object
Using in operator
The in
operator is a binary operator. This operator is also used to check if an object has a property with a specified key. The in
operator also returns a boolean value indicating whether the specified property exists in the object.
Here is the JavaScript code to check if a key or property exists in an object Using in
operator.
// Create an Object const obj = { key1: 'Value1', key2: "value2", key3: 25 }; // Check If key1 is exist in that Object if ('key1' in obj) { console.log("The key exists in the object"); } else { console.log("The key does not exists in the object"); }
In the above program, the in
operator will check if the object obj has a property with the key “key1“. If the specified key is present in the object the in
operator will return true and the code inside the if
block will execute.
Otherwise, it will return false and the code inside the else
block will execute.
Output:
The key exists in the object
Leave a Reply