Skip to content

JavaScript undefined property | Variable value

  • by

The undefined value is a condition where an expression does not have a correct value. JavaScript undefined property indicates that a variable has not been assigned a value, or not declared at all.

When you attempt to access an undefined property, JavaScript will return the value undefined. For example, consider the following code

let obj = { name: "John", age: 30 };
console.log(obj.address); // undefined

Example JavaScript undefined

A simple example code will get an undefined value when you call a non-existent property or method of an object.

Variable not declared:

<!DOCTYPE html>
<html>
<body>

  <script>
   if (typeof myVar === "undefined") {
    console.log("myVar is undefined") 
  } else {
    console.log("myVar is defined")
  } 

</script>

</body>
</html> 

Output:

JavaScript undefined property

How can I check for “undefined” in JavaScript?

Answer: One reason to use typeof is that it does not throw an error if the variable has not been declared.

if (typeof myVar !== "undefined") {
    doSomething();
}

Or use

myVar === undefined

Warning: Please note that === is used over == and that myVar has been previously declared (not defined).

You can use the “in” operator to check if a property exists within an object. For example:

let obj = { name: "John", age: 30 };
if ("address" in obj) {
  console.log(obj.address);
} else {
  console.log("Address property does not exist");
}

Comment if you have any doubts or suggestions on this JS undefined variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading