Q6 of 40 · JavaScript

What is the difference between `null` and `undefined` in JavaScript?

JavaScriptJuniorjavascriptnullundefinedtype-checkingfundamentals

Short answer

Short answer: `undefined` means a variable exists but has no assigned value — the engine's default. `null` is an intentional assignment meaning 'no value here'. Both are falsy. Key quirk: `typeof null === 'object'` is a historical bug in the language.

Detail

These two values both represent absence, but they signal different things.

undefined is the default. Declared but unassigned variables, missing function arguments, and missing object properties all yield undefined. It means the runtime has not set this yet.

null is intentional. A developer sets a value to null to explicitly say "this has no value" — commonly used to reset a reference, signal an empty database result, or initialise an optional property. APIs often return null (rather than omitting a field) to signal an empty record.

Equality quirks: null == undefined is true (loose), but null === undefined is false (strict). A loose null-check like if (x == null) therefore catches both — a useful shorthand some developers intentionally use.

In test automation: API responses often return null for optional fields. Your assertions should distinguish between "field is absent" (undefined) and "field is present but empty" (null) — they often mean different things at the API contract level.

// EXAMPLE

let a;
console.log(a);              // undefined (declared, not assigned)
console.log(typeof a);       // "undefined"

let b = null;
console.log(b);              // null (explicitly set)
console.log(typeof b);       // "object" (historical JS quirk!)

// Equality
console.log(null == undefined);  // true  (loose)
console.log(null === undefined); // false (strict)

// API response — null vs absent field
const response = { userId: 1, deletedAt: null };
console.log(response.deletedAt);    // null — field present, empty
console.log(response.nonExistent);  // undefined — field absent

// JSON serialization difference
JSON.stringify({ a: undefined }); // '{}'          — field dropped
JSON.stringify({ a: null });      // '{"a":null}'  — field kept

// WHAT INTERVIEWERS LOOK FOR

Clear distinction between the two, the typeof null quirk, and loose vs strict equality behaviour. Bonus: the JSON serialization difference — `undefined` is dropped, `null` is kept — which matters for API contract testing.

// COMMON PITFALL

Treating null and undefined as interchangeable. In JSON, undefined is not serialized at all — this has real impact on API contract testing where a missing field vs a null field carry different semantics.