What is null?
null means the variable is intentionally empty — like a placeholder. It tells us that the variable has no value right now but might be given one later. The type of null is an object.
let num = null;
console.log(num); // null
console.log(typeof num); // "object"
Sometimes, null shows up due to errors. For example, when you try to get an HTML element that doesn't exist:
var saveButton = document.getElementById("save");
if (saveButton !== null) {
saveButton.submit();
}
What is undefined?
A variable is undefined when no value has been assigned to it — not even null.
let num;
console.log(num); // "undefined"
Here’s an example where a function doesn’t return anything, so the result becomes undefined:
function greet() {
alert("Hi");
}
let str = greet(); // undefined, because there's no return
Key Differences Between null and undefined
nullis explicitly assigned by the developer.undefinedis automatically assigned when no value is given.
let num1 = null;
let num2;
console.log(num1); // null
console.log(num2); // undefined
Empty string ('') vs null vs undefined
let str = '';
console.log(typeof str); // "string"
console.log(str === null); // false
console.log(str === undefined); // false
Data Types
let num1 = null;
let num2;
console.log(typeof num1); // "object"
console.log(typeof num2); // "undefined"
Comparison Using === and ==
Use === to avoid incorrect comparisons. == can give misleading results.
let num1 = null;
let num2;
console.log(num1 == null); // true
console.log(num2 == undefined); // true
console.log(num1 == undefined); // true (but misleading)
console.log(num2 == null); // true (but misleading)
console.log(num1 === null); // true
console.log(num2 === undefined); // true
console.log(num1 === undefined); // false
console.log(num2 === null); // false
console.log(num1 == num2); // true (incorrect)
console.log(num1 === num2); // false
Using in if Conditions
Both null and undefined are treated as false in conditions.
let num1 = null;
let num2;
if (num1) {
console.log(num1);
} else {
console.log("num1 is null");
}
if (num2) {
console.log(num2);
} else {
console.log("num2 is undefined");
}
Numeric Expressions
null is treated as 0 in math; undefined becomes NaN.
let num1 = null;
let num2;
console.log(num1 + 10); // 10
console.log(num2 + 10); // NaN
String Concatenation
let num1 = null;
let num2;
console.log(num1 + " Hello"); // "null Hello"
console.log(num2 + " Hello"); // "undefined Hello"
Note:
null and undefined are common causes of runtime errors in JavaScript. Always check if a variable is null or undefined before using it.