undefined — default value for uninitialized variables 🆕 null — special value meaning “nothing” or “empty” 🚫
let a; // undefined
let b = null; // null
console.log(a); // undefined
console.log(b); // nullnull and undefined — like two kinds of “emptiness”: one accidental, the other intentional! 📦
undefined — like a room that hasn’t been occupied yet:
// Variable declared but not initialized
let name;
console.log(name); // undefined
// Function returns nothing
function doNothing() {}
console.log(doNothing()); // undefined
// No such property in object
const user = {name: 'John'};
console.log(user.age); // undefinedWhen we get undefined:
null — like an empty box that was intentionally left empty:
// Explicitly set "nothing"
let name = null;
console.log(name); // null
// Clear value
let user = {name: 'John'};
user.name = null; // Explicitly clear
// Not found
function findUser(id) {
// If user not found
return null; // Explicitly "not found"
}When to use null:
let value;
// ❌ Bad — can break
if (value === undefined) { /* ... */ }
// ✅ Good — safe
if (typeof value === 'undefined') { /* ... */ }
// ✅ Even better — short
if (value === void 0) { /* ... */ }let value = null;
// ✅ Simply compare
if (value === null) { /* ... */ }
// ✅ Or check falsiness
if (value == null) { /* ... */ } // Works for both null and undefinedconsole.log(null == undefined); // true (loose comparison)
console.log(null === undefined); // false (strict comparison)
console.log(null == 0); // false
console.log(null == ''); // false
console.log(null == false); // false
console.log(undefined == 0); // false
console.log(undefined == ''); // false
console.log(undefined == false); // false// ✅ Didn't initialize variable
let name;
// ✅ Nothing to return
function process() {
// Return nothing
}
// ✅ No property
const obj = {};
console.log(obj.nonExistent); // undefined// ✅ Explicitly set "empty"
let user = null; // No user yet
// ✅ Clear value
user = {name: 'John'};
user = null; // Explicitly cleared
// ✅ Didn't find data
function findUser(id) {
// Search in database
if (!found) {
return null; // Explicitly "not found"
}
}// ❌ Mistake — not understanding difference
let value1 = null;
let value2;
if (value1 == value2) {
console.log('Same'); // true! But they're different things
}
// ✅ Correct — check precisely
if (value1 === null && value2 === undefined) {
console.log('Different types of emptiness');
}// ❌ Mistake — loose comparison
if (value == null) { /* ... */ } // Works for both null and undefined
// ✅ Correct — strict comparison
if (value === null) { /* ... */ } // Only for nullUnderstanding the difference between null and undefined helps write more precise code! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪