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:

or:

 

Warnings:

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

  2. it is more safe to use hasOwnProperty() function than in operator.

 

Practical examples

Edit

1. Using hasOwnProperty() method

Edit

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

Note:

This solution is safer than in operator.

2. Using in operator

Edit

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

Warning:

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

 

See also

Edit
  1. JavaScript - check if object has property or function

References

Edit
  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
1
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