In this article I am going to discuss about how to check if key exists in javascript object or not with different ways. In javascript check if key exists in object or not is a very common problem but sometimes we will underestimate this problem and that leads to warnings and errors. But for solving this problem there are multiple ways in javascript. The most common solution in javascript to check if key exists or not using in operator.

Introduction to Key Value Pair in Javascript

To know in Javascript check if key exists or not first of all we have to know about the what the key is? The answer is in JavaScript, a “key” typically refers to the identifier used to access the value associated with it in a key-value pair. The key is part of the structure when using objects or maps to store data. If you don’t know about the key-value pair in javascript then don’t worry because will get clear understanding of key-value pair in this article.

In JavaScript, a key-value pair is a fundamental data structure used to associate values (the “values”) with unique identifiers (the “keys”). This structure is often implemented using an object, where each property of the object represents a key-value pair. The key is a string or a symbol, and the value can be of any data type, including numbers, strings, arrays, objects, or functions. Here’s a basic introduction to key-value pairs in JavaScript:

1. Object Literal Notation: You can create key-value pairs using object literal notation by enclosing them within curly braces {}. Here’s an example:

let person = {
  name: "John",
  age: 25,
  gender: "male"
};  //In this example name, age, gender is key and "John", 25, "male" is values for their respective keys.

2. Accessing Object Values: You can access the values of particular object with different ways like using dot operator and using square brackets. For example:

console.log(person.name)// prints John
console.log(person[name])//prints John

3. Modifying the Object Values: You can also modify the values of particular object, add new key-value pairs in that object and delete from object. For example:

person.location = "New York";  // Adding a new key-value pair
person.age = 26; //Modify the Existing key-value pair
delete person.gender //Removes the gender key-value pair

4. Iterating through Key-Value Pairs: You can iterate through the keys or values of an object using for...in loop or Object.keys methods:

for (let key in person) {
  console.log(key, person[key]);
}

//output for above iteration
name John
age 25
gender male

// second way for like above output

Object.keys(person).forEach(key => {
  console.log(key, person[key]);
});

// Or if you want to access all keys together

Object.entries(person).forEach(key => {
  console.log(key);  
});

//output for above iteration
[ 'name', 'John' ]
[ 'age', 25 ]
[ 'gender', 'male' ]


for (let [key, value] of Object.entries(person)) {
  console.log(`${key}: ${value}`);
}

//output for above iteration
name: John
age: 25
gender: male

Javascript Program to Check if Key Exists in Object or not

After knowing about Key and Key-Value pair in javascript now we can go ahead in javascript to check if key exists in object or not. There are so many ways in javascript with that we can check whether the key exists in object or not. Lets discuss all of the approaches.

Approach 1 to Check if Key Exists Using ‘in’ Operator:

The ‘in’ operator returns true if the specified key is present in object otherwise it will return false.

const person = {
    id: 1,
    name: 'John',
    age: 23
}

// check if key exists
const hasKey = 'name' in person;

if(hasKey) {
    console.log('The key exists.');
}
else {
    console.log('The key does not exist.');
}

Approach 2 to Check if Key Exists Using the ‘hasOwnProperty’ method:

The hasOwnProperty method is a built-in method of the Object prototype. It returns a boolean value indicating whether the object has the specified property or not with returning true and false.

const person = {
    id: 1,
    name: 'John',
    age: 23
}

//check if key exists
const hasKey = person.hasOwnProperty('name');

if(hasKey) {
    console.log('The key exists.');
}
else {
    console.log('The key does not exist.');
}

Approach 3 to Check if Key Exists Using ‘optional chaining’ Method:

You can use optional chaining (?.) to safely access nested properties and check if a key exists or not. This is useful when dealing with nested objects, and it avoids throwing an error if a property is undefined.

const details= {
    age: 25,
    gender: "male"
};

if (details?.name !== undefined) {
  console.log('The key "age" exists in the object.');
} else {
  console.log('The key "age" does not exist in the object.');
}

Conclusion

In above article we have discussed what is key-value pair in javascript and different ways of iterating over the key-value pair object, how to modify and delete the key-value pair and also got to know the different ways to check if key exists in object or not. If you want to know about how to make dynamic table in javascript then you can follow this link. Hope you find this article helpful.