Detecting an undefined object property

Home /

Table of Contents

What is Object Property?

An object property is a named value associated with an object. It consists of a name, also called a key, and a value. The value can be of any type, such as a number, a string, a boolean, an array, or even another object. Properties are used to store data and behavior that belongs to the object. They are similar to variables in a class or struct in other programming languages.

Detecting an Undefined Object Property

You can use the ‘typeof’ operator to check if a property of an object is undefined. For example, if you have an object ‘obj’ and you want to check if the property ‘prop’ is undefined, you can use the following code:

JavaScript
if(typeof obj.prop === "undefined") {
    console.log("obj.prop is undefined");
}

Another way to check if a property of an object is undefined is to use the ‘in’ operator. For example, you can use the following code:

JavaScript
if (!('prop' in obj)) {
    console.log("obj.prop is undefined");
}

Also you can use ‘obj.hasOwnProperty(‘prop’)’ method to check if the property exists in the object or not.

JavaScript
if (!obj.hasOwnProperty('prop')) {
    console.log("obj.prop is undefined");
}

It is important to note that ‘undefined’ properties and properties that have been explicitly set to ‘undefined’ will both return ‘true’ when checking with ‘typeof’. If you want to check only properties that were never set, you can use ‘obj.hasOwnProperty(‘prop’)’ method.

Add Property in Object

You can insert a property into an empty object in JavaScript using dot notation or square bracket notation. Here’s an example using dot notation:

JavaScript
const myObject = {}; // create an empty object

myObject.name = "John"; // add a "name" property with value "John"
myObject.age = 30; // add an "age" property with value 30

In this example, we create an empty object called ‘myObject‘ using the object literal syntax ({}). We then add two properties to the object using dot notation (myObject.name and myObject.age), and assign them values.

You can also use square bracket notation to add properties to an empty object. Here’s an example:

JavaScript
const myObject = {}; // create an empty object

myObject["name"] = "John"; // add a "name" property with value "John"
myObject["age"] = 30; // add an "age" property with value 30

In this example, we use square bracket notation (myObject["name"] and myObject["age"]) to add properties to the object, and assign them values.

Both dot notation and square bracket notation can be used to add properties to an object, but square bracket notation is especially useful when the property name contains special characters or spaces.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit
Other Recommended Article