Undefined in JavaScript
Undefined in JavaScript — Concept, Work, and Usage
In this article, we will explore the undefined value in JavaScript in detail. We’ll discuss when and why it occurs, its role, and how to work with it effectively in your code.
undefined is a primitive value in JavaScript that indicates a variable has not been assigned a value. In other words, if a variable is declared but not initialized, it automatically holds the value undefined.
let user;
console.log(user); // undefined
undefined can arise in several scenarios, including:
let user;
console.log(user); // undefined
If a function lacks a return statement or returns nothing explicitly, it automatically returns undefined.
function greet() {
console.log("Hello!");
}
const result = greet();
console.log(result); // undefined
Attempting to access a property that does not exist on an object returns undefined.
const user = { name: "Anna" };
console.log(user.age); // undefined
Accessing an array index that does not exist also results in undefined.
const arr = [1, 2, 3];
console.log(arr[5]); // undefined
While undefined and null are often confused, they have distinct meanings:
let a;
console.log(a); // undefined (literally: variable has no value)
let b = null;
console.log(b); // null (explicitly set to "nothing")