What is the difference between null and undefined in JavaScript?

undefined means a variable has been declared but not assigned a value; null is an intentional explicit assignment meaning "no value".

JavaScript

Overview

Both `null` and `undefined` represent the absence of a value, but they come from different sources and carry different intent. `undefined` is what JavaScript assigns automatically; `null` is what a programmer assigns on purpose to say "this has no value right now".

Key Points

  • •`undefined`: a variable declared but not initialised; a missing function parameter; a non-existent property.
  • •`null`: deliberately assigned to indicate "no value" or "empty". Intentional.
  • •`typeof undefined` → `"undefined"`. `typeof null` → `"object"` (a famous bug in JavaScript).
  • •`null == undefined` → `true` (loose equality). `null === undefined` → `false` (strict).
  • •Both are falsy: `if (!null)` and `if (!undefined)` both enter the block.
  • •Use the `== null` check to catch both: `if (value == null)` is true for both.

Examples

How each arises

javascript
// undefined: JavaScript sets this automatically
let x;
console.log(x); // undefined

const obj = {};
console.log(obj.foo); // undefined (property doesn't exist)

function greet(name) { return name; }
greet();          // undefined (no argument passed)

// null: programmer assigns it explicitly
let user = null;  // intentional: no user loaded yet
user = { name: 'Alice' }; // now there's a user

Equality behaviour

javascript
null == undefined   // true  (special rule in JS)
null === undefined  // false (different types)

null == 0           // false
null == false       // false
undefined == false  // false

Check for both at once (the == null idiom)

javascript
function greet(name) {
  if (name == null) {  // catches both null and undefined
    return 'Hello, stranger!';
  }
  return `Hello, ${name}!`;
}

greet(null);       // 'Hello, stranger!'
greet(undefined);  // 'Hello, stranger!'
greet('Alice');    // 'Hello, Alice!'

Nullish coalescing (??) vs logical OR (||)

javascript
const count = 0;
console.log(count || 10);  // 10  (0 is falsy, so fallback kicks in - bug!)
console.log(count ?? 10);  // 0   (?? only falls back for null/undefined)

const name = '';
console.log(name || 'Anonymous');  // 'Anonymous'
console.log(name ?? 'Anonymous');  // '' (empty string is not null/undefined)

Use ?? when you want to fall back only on null/undefined, not on 0 or "".

Pro Tip

In practice: functions that "have nothing to return" should return `null` explicitly. Relying on `undefined` (implicit return) is fine internally, but returning `null` communicates intent more clearly to callers.