Javascript check if a Key exists in an Object

Javascript check if a Key exists in an Object example; In this tutorial, you will learn How to check if a key exists in a JavaScript object.

Example 1: Check if Key exists in Object using in Operator

To check if a key exists in a JavaScript object, we can use the in operator. The in operator will return true if the key is in the specified object.

const person = {
    name: 'John',
    email: 'john@example.com
}

const hasKey = 'name' in person;

if(hasKey) {
    console.log('The key exists.');
}

The value before the in keyword should be of type string or symbol. Any non symbol value will get automatically coerced to a string.

Example 2: Check if Key Exists in Object Using hasOwnProperty()

We can use the Object.hasOwnProperty method to check if a key exists in an object. The Object.hasOwnProperty method returns true if the key exists in the object and false otherwise.

const person = {
    name: 'John',
    email: 'john@example.com
}

const hasKey = 'person.hasOwnProperty('email');
if (hasKey) {
    console.log('The key exists.');
}

Example 3: Check if a Key exists in an Object with Optional Chaining

We can use the Optional chaining (?.) operator to check if a key exists in an object. If the key exists on the object, the Optional chaining operator will return the key’s value, otherwise it returns undefined.

const person = {
    name: 'Bjorn'
}

console.log(person?.name); // Bjorn
console.log(person?.age); // undefined

if (person?.name !== undefined) {
  // the key exists on the object
}

In the code example we used the Optional chaining operator to check if the name and age keys exist in the object.

Hope these example help you.