How to Check if a Property of a JavaScript Object is Undefined
Before attempting to access a property of a JavaScript object you may want to check it exists so that your program doesn't throw an error. We can do this using the typeof
JavaScript utility.
How to use typeof
typeof
is the correct way to find out if something expected to be an object is indeed an object. typeof
is a general-purpose utility native to JavaScript that returns what a thing is in a string format.
To demonstrate this let's define an array, a number and a string and find out what they are according to JavaScript using typeof
.
let items = [];
let num = 2;
let str = '';
console.log(typeof items);
console.log(typeof num);
console.log(typeof str);
console.log(typeof thing);
object
number
string
undefined
As you can see the first three entries returned are what we would expect them to be and the last returned undefined
. Indeed, we never defined the variable thing
, but the program didn't throw an error when checking using typeof
, it just returned that the variable wasn't defined.
We can apply the same principal to see if a property exists on an object. Let's create an object with some properties and check if the property orange
is defined using typeof
.
let food = {
banana: 2,
apple: 1
}
if (typeof food.orange === 'undefined') {
// is undefined.
}
The above if
statement would find that orange
is undefined on the food
object.
If we wanted to check if a property does exist in the object we can use !==
(strict not equal to).
let food = {
banana: 2,
apple: 1
}
if (typeof food.apple !== 'undefined') {
console.log(food.apple);
}
1
Conclusion
You now know how to check if a property exists in JavaScript and that the typeof
utility is a general-purpose tool for checking what things are.