Null and Undefined
Understand the difference between null and undefined in JavaScript — two distinct primitives that both represent the absence of a value.
Understand the difference between null and undefined in JavaScript — two distinct primitives that both represent the absence of a value.
Both null and undefined mean “no value”, but they come from different places.
undefined is what JavaScript assigns automatically when a value is missing:
let name;console.log(name); // undefined — declared but not assigned
function greet(name) { console.log(name);}greet(); // undefined — argument not passed
const obj = {};console.log(obj.missing); // undefined — property doesn't existYou didn’t do anything. JavaScript did.
null is something you assign intentionally to say “this is empty on purpose”:
let user = null; // no user logged in yetIt’s a signal to other code that the absence is deliberate, not an oversight.
null and undefined are equal with == but not ===:
null == undefined; // truenull === undefined; // falseTo catch both at once, the loose equality check is useful:
if (value == null) { // value is null OR undefined}typeof null returns 'object' — a known bug in JavaScript that can never be fixed for backwards compatibility:
typeof null; // 'object' — wrong, historical bugtypeof undefined; // 'undefined' — correctDon’t rely on typeof to distinguish null from objects. Use === null instead.
undefined: JavaScript is telling you something is missingnull: you are telling your code something is intentionally empty