What is the difference between null and undefined in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
undefined means a value was never set: an unassigned variable, a missing property or a function that returns nothing. null is a value someone assigned on purpose to say "there is no object here".This answer is one piece of Chapter 1: Values and Variables.
Both mean "empty", but they arrive differently, and a test that reads data needs to tell them apart.
JavaScript produces undefined by itself. Read a property the order object does not have, such as order.trackingNumber, and you get undefined. Nobody wrote that value; it is simply absent. null only appears when code assigns it, as the order data does with courier: null to say "no courier yet".
The example shows three more details. typeof null is "object", which MDN calls a bug that cannot be fixed for backward compatibility, so do not use typeof to detect null. null === undefined is false, because they are different values. null == undefined is true, because == converts before it compares.
That last rule is the one useful job left for ==. In label(), qty == null catches both null and undefined and nothing else, so a real quantity of 0 still prints 0 units. For every other comparison, use ===.
const order = { id: 'ORD-4100', city: 'Kochi', courier: null };
console.log(order.courier); // assigned null on purpose
console.log(order.trackingNumber); // never set at all
console.log(typeof null, typeof undefined);
console.log(null === undefined); // different values
console.log(null == undefined); // == treats them as equal
function label(qty) {
return qty == null ? 'quantity missing' : `${qty} units`;
}
console.log(label(undefined), '|', label(null), '|', label(0));null undefined object undefined false true quantity missing | quantity missing | 0 units
{ id: 'ORD-4100', courier: null }. What do response.courier and response.awb return?Try a real drill. No sign-up.
Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free