;

How to Check Whether a Key Exists in an Object in Javascript


Tutorialsrack 19/03/2022 Jquery Javascript

In this article, you’ll learn how to check whether a key exists in an object in javascript. There are mainly two methods to check the existence of a key in JavaScript Object: in operator and hasOwnProperty() Method. 

Here are the examples to check whether a key exists in a javascript object or not.

Example 1:  Using in Operator

In this example, we used the in operator to check if a key exists or not in the javascript object. The in operator is used to check if a specific property exists in an object or its inherited properties (also known as its prototype chain). If the specific property exists, the in operator returns true, otherwise, it returns false.

var obj = {
    price: "900",
    size: ["M", "XL"],
    sort: "desc",
    color: "red"
};

// check if key exists
console.log('color' in obj);
//Output ==> true

console.log('fabric' in obj);
//Output ==> false

Example 2: Using hasOwnProperty() Method

In this example, we used the hasOwnProperty() method to check if a key exists or not in the javascript object. The hasOwnProperty() method is used to check if the object has a specific property as its own property. If the specific property exists, the hasOwnProperty() method returns true, otherwise, it returns false.

var obj = {
    price: "900",
    size: ["M", "XL"],
    sort: "desc",
    color: "red"
};

// check if key exists
console.log(obj.hasOwnProperty('color'));
//Output ==> true

console.log(obj.hasOwnProperty('fabric'));
//Output ==> false

I hope this article will help you to understand how to check whether a key exists in an object in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags