How to Check if an Object Property is undefined in JavaScript
Table of Contents
In JavaScript, you will often have to check if a property is defined on an object. This is important because if you try to access a property that is not defined, you will get an error.
In this post, we will explore the proper way to check if a property is defined on an object.
Check if a property is defined on an object
The best way to check if a property is defined on an object is to use the typeof
operator.
This operator will return the type of the property as a string. If the property is not defined, it will return undefined
.
From here, we can simply do a string comparison to see if the property is defined.
First, let's see how the typeof
operator works by looking at examples.
JAVASCRIPTconst number = 1;
const string = "string";
const boolean = true;
const object = {};
const array = [];
const function_ = function() {};
const list = [1, 2, 3];
typeof number; // 'number'
typeof string; // 'string'
typeof boolean; // 'boolean'
typeof object; // 'object'
typeof array; // 'object'
typeof function_; // 'function'
typeof list; // 'object'
typeof fake; // 'undefined'
Now to check if a property is undefined
just use the typeof
operator and compare it to undefined
.
This also works with objects. Consider this example:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
typeof object.name; // 'string'
typeof object.age; // 'number'
typeof object.fake; // 'undefined'
Here's how you can check if any property is undefined
:
JAVASCRIPTif (typeof object.property === "undefined") {
// do something
}
Conclusion
In this post, we've explored the proper way to check if a property is defined on an object. We also covered the typeof
operator.
Remember, the typeof
operator will return the type of the property as a string. If the property is not defined, it will return undefined
.
Hopefully, you've found this information helpful.
Happy coding!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Using Axios to Pull Data from a REST API