Concepts/JavaScript

null vs undefined

undefined means a variable exists but has no assigned value. null is an intentional assignment meaning "no value." Both represent absence, but with different semantics.

Side-by-Side Comparison

Featureundefinednull
MeaningNot yet assignedIntentionally empty
typeof"undefined""object" (historical bug)
Appears automaticallyYes (uninitialized vars, missing props)No (must be explicitly set)
JSON serializationOmitted from JSONPreserved as null
== comparisonnull == undefined is truenull == undefined is true

Code Examples

undefined

  • Default value for uninitialized variables
  • Returned by functions with no return statement
  • Value of missing object properties
  • Value of missing function arguments
let x            // x is undefined
function foo() {} // foo() returns undefined

const obj = { a: 1 }
obj.b            // undefined (missing property)

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

null

  • Must be explicitly assigned — never appears automatically
  • Represents intentional absence of a value
  • typeof null === "object" (historical bug in JavaScript)
  • Used to clear/reset a variable or DOM reference
let user = null  // intentionally empty

// Clear a reference
let element = document.getElementById('app')
element = null   // help garbage collection

// API responses often use null
const response = { data: null, error: 'Not found' }

typeof null      // "object" (JS bug since 1995)
typeof undefined // "undefined"

When to Use Which

null

When you intentionally want to represent "no value" — clearing references, API responses, initial state that hasn't been fetched yet.

undefined

Generally don't assign undefined explicitly. Let JavaScript use it as the default. If you need "no value," prefer null for clarity of intent.

Common Mistakes

Interview Questions

Why does typeof null return "object"?

It's a bug from the original JavaScript implementation in 1995. Internally, values were stored with a type tag, and null used the same tag as objects (0). This was never fixed for backward compatibility.

What does the nullish coalescing operator (??) do?

`a ?? b` returns b only if a is null or undefined. Unlike `a || b`, it doesn't treat 0, "", or false as "nullish." This makes it safer for default values where falsy values are valid.

Deep Dive