How do you check if an object has a specific property?
Topics
JavaScript
Edit on GitHub
TL;DR
To check if an object has a specific property, you can use the in
operator or the hasOwnProperty
method. The in
operator checks for both own and inherited properties, while hasOwnProperty
checks only for own properties.
How do you check if an object has a specific property?
Using the in
operator
The in
operator checks if a property exists in an object, including properties in the object's prototype chain.
Using hasOwnProperty
The hasOwnProperty
method checks if a property exists directly on the object, not in its prototype chain.
Differences between in
and hasOwnProperty
- The
in
operator checks for both own and inherited properties. - The
hasOwnProperty
method checks only for own properties.