Hiprup

What is the difference between null and undefined?

Both represent "no value", but with different intent.

  • undefined — JavaScript's default: an unassigned variable, a missing argument, or a missing property.

  • null — an intentional, explicit "empty" value that you assign yourself.

  • Comparison — null == undefined is true, but null === undefined is false (different types).

Remember: typeof undefined is "undefined", but typeof null is "object" — a famous language bug.

// undefined — automatic, uninitialized
let x;
console.log(x);                    // undefined
console.log(typeof x);             // 'undefined'

function foo(a, b) {
  console.log(a, b);               // 1, undefined (b not passed)
}
foo(1);

const obj = { name: 'John' };
console.log(obj.age);              // undefined (property missing)

// null — intentional absence
let user = null;                   // Explicitly set to no value
console.log(typeof user);          // 'object' (bug!)

// Comparison
console.log(null == undefined);    // true (loose equality)
console.log(null === undefined);   // false (different types)
console.log(null == 0);            // false
console.log(undefined == 0);       // false
console.log(null == '');           // false

// Practical: check for both
function isNullish(value) {
  return value == null; // Catches both null and undefined
}
// Or: value ?? 'default' (nullish coalescing)
const name = user?.name ?? 'Anonymous';

undefined is automatic (variable not initialized, parameter not passed, property missing). null is explicit (programmer sets it). typeof null = 'object' is a historical bug. == treats them as equal, === does not. The value == null shorthand catches both.

Optional chaining (?.) and nullish coalescing (??) are modern null/undefined handling.

undefined = automatic/uninitialized, null = intentional absence. Know typeof null = 'object' (bug).

The == null shorthand and ?. / ?? operators for null-safe access are practical modern tools.

What is the difference between null and undefined? | Hiprup