How to Check If a JavaScript Object Property Is undefined?

In a JavaScript, the correct way to check if an object property is undefined is to use the typeofoperator.
The typeof operator returns a string indicating the type of the unevaluated operand.
For example:
console.log(typeof 42);
// expected output: "number"

console.log(typeof 'blubber');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof declaredButUndefinedVariable);
// expected output: "undefined";
If the value is not defined, typeof returns the ‘undefined’ string.

How to check if a JavaScript object property is undefined?

Let's create a user object with the following properties in it:
// using Object Literals
var user = {
    emailId : 'ramesh@gmail.com',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
};
Note that firstName and lastName properties not added to the above user object.
Now, let's create a isUndefined() method and test firstName and lastName properties:
function isUndefined(user) {
    if(typeof user.firstName === 'undefined'){
        console.log("User first name is undefined");
    }

    if(typeof user.lastName === 'undefined'){
        console.log("User last name is undefined");
    }
}
Let's call the above function:
isUndefined(user);
Output:
User first name is undefined
User last name is undefined

Complete code

// using Object Literals
var user = {
    emailId : 'ramesh@gmail.com',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
};

function isUndefined(user) {
    if(typeof user.firstName === 'undefined'){
        console.log("User first name is undefined");
    }

    if(typeof user.lastName === 'undefined'){
        console.log("User last name is undefined");
    }
}

isUndefined(user);
Output:
User first name is undefined
User last name is undefined

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments