Languages
[Edit]
EN

JavaScript - check if object has key

0 points
Created by:
Jacob
532

In this article, we would like to show you how to check if object has certain key in JavaScript.

Quick solutions:

if (Object.prototype.hasOwnProperty.call(myObject, 'key')) {
    // ...
}

or:

if ('key' in myObject) {
    // ...
}

 

Warnings:

  1. using myObject.hasOwnProperty() construction may lead to mistakes by function overriding.
    Incorrect code:

    if (myObject.hasOwnProperty('key')) {
        // ...
    }
  2. it is more safe to use hasOwnProperty() function than in operator.

 

Practical examples

1. Using hasOwnProperty() method

In this example we use hasOwnProperty() method to check if user object has age property.

// ONLINE-RUNNER:browser;

const user = { id: 1, name: 'Tom', age: 25 };

if (Object.prototype.hasOwnProperty.call(user, 'name')) {
    console.log('The user object contains name property.');
}

Note:

This solution is safer than in operator.

2. Using in operator

In this example we use in operator to check if user object has age property.

// ONLINE-RUNNER:browser;

const user = { id: 1, name: 'Tom', age: 25 };

if ('name' in user) {
    console.log('The user object contains name property.');
}

Warning:

The in operator matches all object keys, including those in the object's prototype chain.

 

See also

  1. JavaScript - check if object has property or function

References

  1. in operator - JavaScript | MDN
  2. Object.prototype.hasOwnProperty() - JavaScript | MDN

Alternative titles

  1. JavaScript - check if object has certain key
  2. JavaScript - check if object contains certain key
  3. JavaScript - check if object has property / key
  4. JavaScript - determine whether object has given property
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join