Languages
[Edit]
EN

JavaScript - check if key exists in object

0 points
Created by:
Saim-Mccullough
688

In this article, we would like to show you how to check if key exists in object working with JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var object = { keyName: 'A'};

console.log('keyName' in object);  // true

 

Practical example

In this example, we use for...in statement to check if a key exists in the object. This way true value is returned even when the key value is undefined.

// ONLINE-RUNNER:browser;

var object = { keyName1: 'A', keyName2: undefined };

console.log('keyName1' in object); // true
console.log('keyName2' in object); // true (key exists but value is undefined)

console.log('keyName3' in object); // false

Alternative solution

You can also use hasOwnProperty() method to achieve the same result as above.

// ONLINE-RUNNER:browser;

var object = { keyName1: 'A', keyName2: undefined };

console.log(object.hasOwnProperty('keyName1')); // true
console.log(object.hasOwnProperty('keyName2')); // true

console.log(object.hasOwnProperty('keyName3')); // false

See also

  1. JavaScript - for...in statement

References

  1. for...in - JavaScript | MDN
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