jsonjavascriptdebuggingtutorial

null vs undefined in JSON — How to Handle Missing Values

·5 min read

null vs undefined — The Core Difference

JSON recognizes null as a valid value. JSON does not recognize undefined — it is a JavaScript-only concept that does not exist in the JSON specification.

javascript
JSON.parse('null');        // ✓ returns null
JSON.parse('undefined');   // ✗ SyntaxError
JSON.parse('"undefined"'); // ✓ returns the string "undefined"

What JSON.stringify Does with undefined

This is where most bugs come from. JSON.stringify silently drops object properties that are undefined:

javascript
const user = {
  name: 'Ravi',
  middleName: undefined, // dropped!
  age: 28,
};

JSON.stringify(user);
// '{"name":"Ravi","age":28}'
// middleName is gone — no error, no warning

If a property is required in your API, this silent drop will cause a 400 or 422 error that is hard to diagnose.

In arrays, undefined becomes null:

javascript
JSON.stringify([1, undefined, 3]);
// '[1,null,3]'

Common Bug Patterns

Bug 1: Sending undefined instead of null

javascript
const body = {
  userId: user.id,
  referral: promoCode || undefined, // if no promo, property is dropped
};

// API receives: {"userId": 42}
// API expected: {"userId": 42, "referral": null}

Fix — use null explicitly:

javascript
const body = {
  userId: user.id,
  referral: promoCode || null, // property is always present
};

Bug 2: Accessing deeply nested fields that might not exist

javascript
const city = data.user.address.city; // TypeError if address is null/undefined

Fix — use optional chaining:

javascript
const city = data?.user?.address?.city ?? 'Unknown';

Bug 3: Comparing null and undefined

javascript
const x = null;
x === null;      // true
x === undefined; // false
x == null;       // true  (== checks both null and undefined)
x == undefined;  // true

Use `=== null` when you specifically mean JSON null. Use `== null` when you mean "absent from JSON or not set in JS".

Safe Nested Access Pattern

javascript
// Parse API response safely
function getNestedValue(obj, path, fallback = null) {
  return path.split('.').reduce((acc, key) => {
    return acc != null ? acc[key] : fallback;
  }, obj) ?? fallback;
}

const city = getNestedValue(apiResponse, 'user.address.city', 'Unknown');

Or with optional chaining (modern JavaScript):

javascript
const city     = response?.data?.user?.address?.city ?? 'Unknown';
const firstTag = response?.data?.tags?.[0] ?? null;

Replace undefined with null Before Serializing

To ensure no properties are accidentally dropped when converting to JSON:

javascript
function undefinedToNull(obj) {
  return JSON.parse(JSON.stringify(obj, (_, v) => v === undefined ? null : v));
}

const safe = undefinedToNull({ name: 'Ravi', score: undefined });
// { name: 'Ravi', score: null }
JSON.stringify(safe);
// '{"name":"Ravi","score":null}'

Best Practice: Be Explicit

Never rely on undefined to mean "not present." Use null for a JSON property that has no value. Omit the property entirely only when it truly does not apply to this resource type.

javascript
// CLEAR — null means the field exists but has no value
{ "middleName": null }

// CLEAR — field is omitted because it is not applicable
{}

// AMBIGUOUS — JavaScript undefined leaking into your API
{ "middleName": undefined } // serializes as {} — same as above, silently

Validate your JSON output at /json-validator to make sure expected fields are present and not silently dropped.

Try JSON Formatter

Inspect how null values appear in your serialized JSON output.