In this post we will be covering how to check if an object property exists but is undefined in JavaScript with as little technical jargon as possible so you will have everything you need right here without having to look any further!
If you need to check in JavaScript if an object property exists but is undefined then it becomes a little trickier than simply using typeof.
In this post we are going to look at how you can check if a property exists in JavaScript.
How to check if an object property exists but is undefined in JavaScript
The easiest way to check if an object property exists but is undefined in JavaScript is to make use of the Object.prototype.hasOwnProperty method which will let you find properties in an object.
The problem of checking if an undefined property exists in an object comes from when you reference a property that does not exist then it will return undefined, just like if you have a property that does exist where the value is undefined.
Here is an example of the problem:
const myObj = { a: undefined }
myObj.a // undefined
myObj.b // undefined
By using the Object.prototype.hasOwnProperty method we can check if a property exists or not even if it is undefined.
Here is an example of how you can use hasOwnProperty to perform this check:
const myObj = { a: undefined }
myObj.hasOwnProperty("a") // true
myObj.hasOwnProperty("b") // false
As you can see when you use hasOwnProperty it will return a boolean or true or false if the property exists even if the property is undefined.
Why typeof does not work to check if an object property exists but is undefined
The reason why we can’t check using typeof
is because if the property does exist but is undefined then using typeof will return the same result as when the property does not exist.
Here is an example of this problem:
const myObj = { a: undefined }
typeof myObj.a // "undefined"
typeof myObj.b // "undefined"
Summary
There we have how to check if an object property exists but is undefined in JavaScript, if you want more like this be sure to check out some of my other posts!