Problem Statement
What is the key difference between null and undefined?
Explanation
Undefined is JavaScript's way of saying this variable exists but has no value yet.
JavaScript automatically assigns undefined when:
You declare a variable but do not initialize it.
You access an object property that does not exist.
A function has no return statement.
A function parameter is not provided.
Null is your way of saying this variable intentionally has no value. You explicitly assign null to represent emptiness.
Think of it like parking spaces:
Undefined is an empty space with no sign. Nothing has parked there yet.
Null is an empty space with a Reserved sign. You intentionally marked it as empty.
Both are falsy values but have different meanings.
Code Solution
SolutionRead Only
// undefined - JavaScript sets it automatically
let a;
console.log(a); // undefined (variable declared but not assigned)
let person = { name: 'John' };
console.log(person.age); // undefined (property doesn't exist)
function test() {
// no return statement
}
console.log(test()); // undefined (no return value)
function greet(name) {
console.log(name); // undefined if not passed
}
greet(); // undefined (parameter not provided)
// null - You set it intentionally
let user = null; // Intentionally empty
let data = null; // Waiting for data
let response = null; // No response yet
// Checking for both
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object' (bug)
console.log(undefined == null); // true (loose equality)
console.log(undefined === null); // false (different types)
// Practical usage
if (value === undefined) {
console.log('Never assigned');
}
if (value === null) {
console.log('Intentionally empty');
}
if (value == null) {
console.log('Either undefined or null');
}