How To Check Undefined In JavaScript?

JavaScript objects are dynamic objects and can be created and deleted in a fast way. Sometimes we may need to check the object or other elements if they are defined or undefined. There are different ways to check if the object is undefined in JavaScript.

Check with console.log() Method

The console.log() method is created in order to log different values into the web browser console. The value or representation of the provided object is directly printed in the browser log. If the provided object is not defined the undefined is printed in the browser log.

console.log(myobject)

Check with windows Object

The HTML Dom or JavaScript provides the window object in order to access the current browser window objects. We can use this in order to access an object defined inside the window with the help of the if statement.

if(window.myobject){
   console.log("Defined")
}
else{
   console.log("Undefined")
}

Check with typeof() Method

JavaScript provides the typeof() function in order to check the type of the provided object. We can use the typeof() method in order to check if the provided object is defined or undefined. If the object is undefined the string undefined is returned.

if(typeof(myobject)=="defined"){
   console.log("Defined")
}
else{
   console.log("Undefined")
}

Check with if Statement

The if statement is used to check different conditions and boolean values. We can use the if statement in order to check if the object is defined or undefined.

if(myobject){
   console.log("Defined")
}
else{
   console.log("Undefined")
}

Leave a Comment