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.
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:
const user = {
name: 'Ravi',
middleName: undefined, // dropped!
age: 28,
};
JSON.stringify(user);
// '{"name":"Ravi","age":28}'
// middleName is gone — no error, no warningIf 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:
JSON.stringify([1, undefined, 3]);
// '[1,null,3]'Common Bug Patterns
Bug 1: Sending undefined instead of null
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:
const body = {
userId: user.id,
referral: promoCode || null, // property is always present
};Bug 2: Accessing deeply nested fields that might not exist
const city = data.user.address.city; // TypeError if address is null/undefinedFix — use optional chaining:
const city = data?.user?.address?.city ?? 'Unknown';Bug 3: Comparing null and undefined
const x = null;
x === null; // true
x === undefined; // false
x == null; // true (== checks both null and undefined)
x == undefined; // trueUse `=== null` when you specifically mean JSON null. Use `== null` when you mean "absent from JSON or not set in JS".
Safe Nested Access Pattern
// 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):
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:
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.
// 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, silentlyValidate your JSON output at /json-validator to make sure expected fields are present and not silently dropped.