In JavaScript, “undefined” is a primitive type that represents a variable that has been declared but not assigned a value. It is also used as the default return value for functions that do not have a return statement or for variables that do not exist.
For example, if you declare a variable but do not assign a value to it, like this:
let myVariable;
Then, if you try to access the value of “myVariable” before assigning a value to it, you will get “undefined”:
console.log(myVariable); // Output: undefined
It’s important to note that “undefined” is a primitive value in JavaScript and not an object. However, it is considered a type of its own in the language.
Type of undefined in JavaScript example
Simple example code that demonstrates the “undefined” type in JavaScript:
<!DOCTYPE html>
<html>
<body>
<script>
let myVariable;
console.log(myVariable);
function myFunction() {
// do not return a value
}
console.log(myFunction());
let myObject = {};
console.log(myObject.myProperty);
</script>
</body>
</html>
Output:
![Type of undefined in JavaScript](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2023/04/Type-of-undefined-in-JavaScript.jpg?resize=322%2C162&ssl=1)
How to handle undefined in JavaScript?
Answer: In JavaScript, handling “undefined” can be important to prevent unexpected errors or behavior in your code. Here are some common ways to handle “undefined”:
1. Check if a variable is undefined using the “typeof” operator:
let myVariable;
if (typeof myVariable === 'undefined') {
// handle the undefined variable
}
2. Use default values when dealing with potentially undefined variables:
let myVariable;
let myValue = myVariable || 'default';
3. Use optional chaining (available from ES2020) to access properties of potentially undefined objects:
let myObject = {
prop1: {
prop2: 'value'
}
};
let myValue = myObject.prop1?.prop2; // use "?" to handle undefined object properties
4. Return a default value from a function if it doesn’t have a meaningful result:
function myFunction(myArgument) {
if (typeof myArgument === 'undefined') {
return 'default';
}
// handle the meaningful result
}
Comment if you have any doubts or suggestions on this Js undefined topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version