Undefined in JavaScript
Undefined is a type of Data type in JavaScript. It is a primitive value undefined, when a variable is declared and not initialized or not assigned with any value. By default, the variable was stored with an Undefined value.
Undefined is a global read-only variable that represents the value Undefined. Undefined is a type of primitive type
Syntax:
You don’t explicitly create undefined
. It’s automatically assigned to variables that lack a value:
let variable = undefined;
// or
let x;
Both no and variable contain an undefined value.
JavaScript Undefined Examples
1. undefined Value in Variables
When a variable is declared or not initialized but not assigned with any value then JavaScript automatically assigns it to an “undefined” value.
Example: In the below example, the variable name is declared but not assigned with any value, so it gets an Undefined value:
let newVar;
console.log(newVar)
Output
undefined
2. undefined Value in Functions
A method or statement also returns undefined. If a variable was assigned with a function that does not return any value, then the JavaScript assigns an undefined value to that variable.
Example: In the below example sayhi() function actually outputs and returns nothing. We assigned the sayhi function to the x variable, so we get an Undefined value in the x variable as the sayhi() function returns nothing.
function sayhi(name) {
console.log(`hi ${name}`);
}
x = sayhi('hike');
console.log(`value in x= ${x}`);
Output
hi hike value in x= undefined
3. undefined value in Object Properties
Accessing a property that doesn’t exist in an object returns undefined
: Let’s understand with the below example code:
Example:
const person = { name: "Alice" };
console.log(person.age); // Output: undefined
Output
undefined
How to Check for undefined value
To check for undefined value , we can use the typeof to check if the value is undefined or not:
let myVariable;
if (typeof myVariable === "undefined") {
console.log("myVariable is undefined");
} else {
console.log("myVariable is defined");
}
Output
myVariable is undefined
Practical Use Cases of undefined values
- Handle optional function parameters.
- Check if an object property exists before accessing it.
- Detect uninitialized variables during debugging.
Remember, understanding undefined
is essential for writing reliable and bug-free JavaScript code!