DEV Community

Cover image for Check if a key exists in JavaScript object?
Abdus Shohid Shakil
Abdus Shohid Shakil

Posted on

Check if a key exists in JavaScript object?

In development, we often need to check whether a key exists in an object or not. You may know one or two way to do it, but there are some other methods worth exploring. If you're interested in learning more, keep reading.

In this blog, I will demonstrate four different ways to perform this check. Each method has its pros and cons, so it's essential to understand all of them. This way, when the need arises, we can choose the most suitable approach.


Using in operator.

In JavaScript in operation used to check a property exist in an object or not. It return true if exist else false.
Note: It also includes properties that come from inheritance or prototype chaining. So, when you need to check purely for properties of the object itself, it may not return the desired result.

Complexity is O(1).



const user  = {
    fullName: "Shakil Ahmed",
    age: 22,
    isStudent: true,
};

// structure "keyName" in object
console.log("fullName" in  user); // true
console.log("age" in  user); // true
console.log("institute" in  user); // false


Enter fullscreen mode Exit fullscreen mode

Using hasOwnProperty method.

hasOwnProperty is an object method, it's purpose is same as in operator. But different is it checks only object own property excluding inheritance or prototype chaining property. So it return pure result.

Put the key name in method argument and it will return true if it contain key else false.

Complexity is O(1), so performance is also good.



const user  = {
    fullName: "Shakil Ahmed",
    age: 22,
    isStudent: true,
};

console.log(user.hasOwnProperty("fullName")); // true
console.log(user.hasOwnProperty("age"));// true
console.log(user.hasOwnProperty("institute")); // false


Enter fullscreen mode Exit fullscreen mode

Using optional chaining

Optional chaining is an ES11 feature that helps access values without throwing Uncaught TypeError errors. When a key doesn't exist, it returns undefined; otherwise, it returns the value. To convert the result into a boolean value, prepend !! to the expression.

Complexity to check is O(1), so performance is good.



const user  = {
    fullName: "Shakil Ahmed",
    age: 22,
    isStudent: true,
};

console.log(user?.fullName); // Shakil Ahmed
console.log(!!user?.fullName); // true
console.log(user?.id); // undefined
console.log(!!user?.id); // false


Enter fullscreen mode Exit fullscreen mode

However, it has a limitation: if the value is false, 0, undefined, or null any falsy value it will return false, even if the key exists in the object.



const user  = {
    fullName: "Shakil Ahmed",
    age: 22,
    isStudent: false,
    a: 0,
    b: undefined,
    c: null,
    d: NaN,
};


Enter fullscreen mode Exit fullscreen mode


console.log(user?.isStudent); // false
console.log(!!user?.isStudent); // false

console.log(user?.a); // 0
console.log(!!user?.a); // false

console.log(user?.b); // undefined
console.log(!!user?.b); // false

console.log(user?.c); // null
console.log(!!user?.c); // false

console.log(user?.d); // NaN
console.log(!!user?.d); // false


Enter fullscreen mode Exit fullscreen mode

in the above examples, isStudent, a, b, c, d variables exist in the object, but this technique returning false only due to falsy values.


Comparing all keys

This process involves manually traversing over all keys of the object to check if a specific key exists.

Complexity: Traversing the entire object results in a time complexity of O(n), where n is the number of keys in the object.



const user  = {
    fullName: "Shakil Ahmed",
    age: 22,
    isStudent: false,
    a: 0,
    b: undefined,
    c: null,
    d: NaN,
};


Enter fullscreen mode Exit fullscreen mode


const  isKeyExistInObject  = (obj, key) => {
    // here '!!' is to convert result in boolean you also can use Boolean() constructor.
    return  !!Object.keys(obj).find((eachKey) =>  eachKey  ===  key);
};


Enter fullscreen mode Exit fullscreen mode

In the above code, I've created a function to check the existence of a key. Here, I convert all keys of the object into an array using Object.keys(obj). Then, I traverse that array and check if it contains the specified key. If the key is found, find returns that eachKey; otherwise, it returns undefined. Using !! converts this result into a boolean. You can also use the Boolean(value) constructor.

The isKeyExistInObject function returns a boolean value.



console.log(isKeyExistInObject(user, "fullName")); // true
console.log(isKeyExistInObject(user, "first name")); // false
console.log(isKeyExistInObject(user, "age")); // true
console.log(isKeyExistInObject(user, "isStudent")); // true
console.log(isKeyExistInObject(user, "a")); // true
console.log(isKeyExistInObject(user, "b")); // true
console.log(isKeyExistInObject(user, "c")); // true
console.log(isKeyExistInObject(user, "d")); // true
console.log(isKeyExistInObject(user, "notExist")); // false


Enter fullscreen mode Exit fullscreen mode

Note: Although this method is slightly more complex than other techniques, it works for any falsy values.


Example with nested objects

Here is a nested object and here we will use all of the above techniques

Example object:



const  user  = {
    name: "Shakil",
    age: 22,
    studentData: {
        id: "123",
        bachelor: "CSE",
        countryData: {
            country: "Bangladesh",
            capital: "Dhaka",
            language: "Bangla",
        },
    },
};


Enter fullscreen mode Exit fullscreen mode

Using in:



// ========== is "name" exist
console.log("name"  in  user); // true

// ========== is "studentData" exist
console.log("studentData"  in  user); // true

// ========== is "id" exist
console.log(
    "studentData"  in  user  &&  "id"  in  user.studentData
); // true

// ========== is "language" exist
console.log(
    "studentData"  in  user  &&
    "countryData"  in  user.studentData  &&
    "language"  in  user.studentData.countryData
); // true


Enter fullscreen mode Exit fullscreen mode

Using hasOwnProperty:



// ========== is "name" exist
console.log(user.hasOwnProperty("name")); // true

// ========== is "studentData" exist
console.log(user.hasOwnProperty("studentData")); // true

// ========== is "id" exist
console.log(
    user.hasOwnProperty("studentData") && 
    user.studentData.hasOwnProperty("id")
); // true

// ========== is "language" exist
console.log(
    user.hasOwnProperty("studentData") &&
    user.studentData.hasOwnProperty("countryData") &&
    user.studentData.countryData.hasOwnProperty("language")
); // true


Enter fullscreen mode Exit fullscreen mode

Using optional chaining



// ========== is "name" exist
console.log(!!user?.name); // true

// ========== is "studentData" exist
console.log(!!user?.studentData); // true

// ========== is "id" exist
console.log(
    !!user?.studentData  &&  !!user.studentData?.id
); // true

// ========== is "language" exist
console.log(
    !!user?.studentData  &&
    !!user.studentData?.countryData  &&
    !!user.studentData.countryData?.language
); // true


Enter fullscreen mode Exit fullscreen mode

Comparing all keys :



const  isKeyExistInObject  = (obj, key) => {
    return  !!Object.keys(obj).find(
        (eachKey) =>  eachKey  ===  key
    );
};

// ========== is "name" exist
console.log(isKeyExistInObject(user, "name")); // true

// ========== is "studentData" exist
console.log(isKeyExistInObject(user, "studentData")); // true

// ========== is "id" exist
console.log(
    isKeyExistInObject(user, "studentData") &&
    isKeyExistInObject(user.studentData, "id")
); // true

// ========== is "language" exist
console.log(
    isKeyExistInObject(user, "studentData") &&
    isKeyExistInObject(user.studentData, "countryData") &&
    isKeyExistInObject(user.studentData.countryData, "language")
); // true


Enter fullscreen mode Exit fullscreen mode

In summary, knowing different ways to check for keys in JavaScript objects empowers developers to write more efficient and reliable code. Each method offers its own advantages, allowing flexibility in handling various scenarios. By familiarizing yourself with these techniques, you can enhance your JavaScript skills and tackle object-related challenges with ease. Keep exploring and experimenting to find the approach that best fits your needs. Happy coding!

Image description

Top comments (7)

Collapse
 
ccondrup profile image
Chris

Please note:

Object.hasOwn() is recommended over hasOwnProperty(), in browsers where it is supported.

Ref: developer.mozilla.org/en-US/docs/W...

Collapse
 
jgdevelops profile image
Julian Gaston

Awesome article. I completely had forgotten about the "in" option haha. Thanks for the reminder. Great stuff!

Collapse
 
developerhub profile image
Abdus Shohid Shakil

My pleasure 😊😊😊.

Collapse
 
xaan profile image
Xaan Amaan

Too good

Collapse
 
alexanderlamdan profile image
Alexander

I think I will save that article, damn it is really good for me after 3 years of take a break from coding

Collapse
 
dipayansukul profile image
Dipayan Sukul

Nice article. Helped me to remember the in operator

Collapse
 
debajit13 profile image
Debajit Mallick

Amazing article. I really liked the explanation.