How to Check If a Key Exists in a JavaScript Object

javascript

Loading

Hello Nerds

Checking if a specific key exists in a JavaScript Object is a common task in programming. We will here describe some most common patterns with which you can get check if key exists in a Javascript Object

In the first way, you can use very simple way in operator to check if a particular key or property exists in your javascript object. The operator returns true if the specified key existing in the object, otherwise it will return false

// This is a Sample object
var myCar = {
    make: "Tata",
    model: "Punch",
    year: 2024
};

// This line Test if a key exists in the object
if("model" in myCar === true) {
    alert("Key Exists in the object");
} else {
    alert("Key doesn't exist in the object");
}

Lets deep dive a little bit more, here if you set the property of an object to undefined and if you do not delete it, then the in operator will return true for that specific property. lets see this with an example.

// This is a Sample object
var myCar = {
    make: "Tata",
    model: "Fortuner",
    year: 2024
};

// Setting a property to undefined
myCar.model = undefined;

// Deleting a property
delete myCar.year;

// Test if properties exist
console.log("make" in myCar);  // Prints: true
console.log("model" in myCar); // Prints: true
console.log("year" in myCar);  // Prints: false

We have seen in operator here to check if key exists in our code or not with true and false statement

There are more ways to do this let have some examples:

  1. Using the in Operator
const obj = { 
    make: "Tata",
    model: "Fortuner",
    year: 2024
};
console.log('model' in obj); // true

2. Using hasOwnProperty() Method

The hasOwnProperty() method checks if the key exists directly on the object, ignoring inherited properties.

const obj = {    
  make: "Tata",
  model: "Fortuner",
  year: 2024 
  };
console.log(obj.hasOwnProperty('model')); // true

3. Using undefined Check

You can check if the value of the key is undefined, but this method can be less reliable if the key exists and its value is actually undefined.

const obj = { 
  make: "Tata",
  model: "Fortuner",
  year: 2024 
};
console.log(obj.model !== undefined); // true

4. Using Object.keys()

The Object.keys() method returns an array of the objectโ€™s own property names. You can check if the array includes the specified key.

const obj = { 
  make: "Tata",
  model: "Fortuner",
  year: 2024 
};
console.log(Object.keys(obj).includes('model')); // true

Depending on your specific needs, you can use any of these methods to check for the existence of a key in a JavaScript object. The in operator and hasOwnProperty() method are generally the most straightforward and reliable choices.

Also Read these blogs

About Post Author