null vs undefined

Difficulty: Beginner

Question

What is the difference between null and undefined in JavaScript?

Answer

Both null and undefined represent "absence of value" but they serve different purposes:

- undefined: variable has been declared but not assigned a value. It is the default value assigned by JavaScript. - null: an intentional assignment indicating "no value" or "empty". It is explicitly set by the programmer.

Key differences: 1. typeof undefined === "undefined", typeof null === "object" (historic bug) 2. undefined is the default for uninitialized variables, missing function args, missing object properties 3. null must be explicitly assigned 4. null == undefined is true (loose), null === undefined is false (strict)

Code examples

undefined Scenarios

// Declared but not assigned
let a;
console.log(a); // undefined

// Missing function parameter
function greet(name) {
  console.log(name);
}
greet(); // undefined

// Non-existent object property
const obj = { x: 1 };
console.log(obj.y); // undefined

// Function with no return
function doNothing() {}
console.log(doNothing()); // undefined

console.log(typeof undefined); // "undefined"

JavaScript assigns undefined automatically in these cases.

null Usage

// Intentional empty value
let user = null; // user will be assigned later
console.log(user); // null
console.log(typeof null); // "object" (known JS bug)

// Clearing a reference
let data = { key: "value" };
data = null; // explicit cleanup

// Checking for both
function isEmpty(val) {
  return val == null; // catches both null and undefined
}
console.log(isEmpty(null));      // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty(0));         // false
console.log(isEmpty(""));        // false

null is used intentionally. The == null check is a common shorthand for checking both null and undefined.

Key points

Concepts covered

null, undefined, Type Checking, Default Values