How to check if a key exists in object - JS

Mo Ibra

Mo Ibra

Jan 7, 2023

In this article we will learn how to check if a key exists in object in JavaScript.

It is very common to check if a key exists in object in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to check if a key exists in object.

Imagine we have object like this:

const myObject = {
    name: "John",
    age: 30,
    country: "USA"
}

And we want to check if name key is exists on this object or not.

Expected output will be:

true

Because key is exists.

How to solve this problem?

This problem is easy, and there is more than one solution to it, and we will explain all the solutions in detail, such as:

  • Using in operator.
  • Using Optional Chaining
  • Using Object.hasOwn

Check if key exists using in operator

We can use in operator to check if key exists or not.

Let's see an example

// Object
const myObject = {
    name: "John",
    age: 30,
    country: "USA"
}

// Tests:
console.log('name' in myObject);
console.log('age' in myObject);
console.log('skills' in myObject);
console.log('country' in myObject);

Output

true
true
false
true

Check if key exists using Optional Chaining

WE can use optional chaining to check if key exists in object as well.

Example

// Object
const myObject = {
    name: "John",
    age: 30,
    country: "USA"
}

// Tests
console.log(myObject?.name);
console.log(myObject?.age);
console.log(myObject?.skills);
console.log(myObject?.country);

Output

John
30
undefined
USA

Check if key exists using Object.hasOwn

We can use Object.hasOwn method to solve our problem as well.

Let's see an example

// Object
const myObject = {
    name: "John",
    age: 30,
    country: "USA"
}

// Tests:
console.log(Object.hasOwn(myObject, 'name'));
console.log(Object.hasOwn(myObject, 'age'));
console.log(Object.hasOwn(myObject, 'skills'));
console.log(Object.hasOwn(myObject, 'country'));

Output

true
true
false
true

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: