What is the difference between null and undefined?
undefined means a value was never assigned: JavaScript gives it to you automatically. null means 'no value' and is set on purpose by the programmer. They are loosely equal (null == undefined) but not strictly equal.
Explain it simply
Think of a hostel room allotment form. If the "Room number" field is blank because nobody filled it yet, that is undefined. If the warden writes "No room" on purpose, that is null. Both mean "nothing", but one is accidental and one is deliberate.
JavaScript produces undefined on its own in many places:
- a declared variable with no value
- a missing object property
- a function parameter that was not passed
- a function with no
return
null never appears unless some code assigns it.
Example
let seat;
const passenger = { name: "Ravi" };
function book() {}
console.log(seat === undefined); // Output: true
console.log(passenger.age === undefined); // Output: true
console.log(book() === undefined); // Output: true
let coupon = null; // set on purpose
console.log(typeof coupon); // Output: object
console.log(typeof seat); // Output: undefined
console.log(null == undefined); // Output: true
console.log(null === undefined); // Output: false
console.log(null + 1); // Output: 1null + 1 gives 1 because null converts to 0, while undefined + 1 gives NaN.
What to say in the interview
"undefined is the default 'not assigned' value that the engine gives you. null is an intentional empty value that I assign myself, for example to clear a selected item. They are loosely equal to each other and to nothing else, so value == null is a handy check for both. In numbers, null becomes 0 and undefined becomes NaN."
Common mistakes
- Assigning
undefinedyourself to mean "empty". Prefernullso readers know it was intentional. - Using
value == nullwithout knowing it also matchesundefined.