How to Check if a Property is Undefined in JavaScript

Nov 24, 2021

To check if an object property key was equal to undefined you can do:

if (obj[key] === undefined) {

The potential problem with this approach approach is that if obj doesn’t have the property, it will also return true.

Checking if the property exists

To check if the object has the property, you can use in operator or hasOwnProperty() function.
These paths will tell you if the object property exists on the object.

const obj = { name: '', location: 'Florida', helpful: true };

'building' in obj; 
obj.building === undefined; 

You can combine these two sections to check if an object has a property and that property is undefined:

function hasUndefinedKey(obj, key) {
  return key in obj && obj[key] === undefined;


function hasUndefinedKey(obj, key) {
  return obj.hasOwnProperty(key) && obj[key] === undefined;

More Fundamentals Tutorials

Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here