null in JSON (No undefined)
Understand how JSON handles null values and why undefined does not exist in JSON. Learn the correct way to represent missing or absent data in JSON documents.
Detailed Explanation
In JSON, null is a first-class data type representing the intentional absence of a value. The value undefined, which is a core concept in JavaScript, does not exist in the JSON specification at all. This distinction is a frequent source of confusion for JavaScript developers.
What null means in JSON:
The literal null (always lowercase) indicates that a key exists but has no meaningful value. It is distinct from an empty string (""), the number zero (0), a boolean false, or an empty object ({}). For example, {"middleName": null} communicates that the middleName field is present in the schema but the user has not provided one. This is different from omitting the key entirely, which implies the field may not be part of the schema.
Why undefined is excluded:
JSON is a data interchange format designed to be language-agnostic. The concept of undefined is specific to JavaScript and a few other languages. In most programming languages, there is no equivalent concept — a variable either has a value or it does not exist. Including undefined in JSON would create ambiguity in languages that do not support it. Douglas Crockford deliberately limited JSON to types that map cleanly across all major programming languages.
What happens to undefined in JavaScript:
When you call JSON.stringify() on a JavaScript object, any properties with an undefined value are silently omitted from the output:
JSON.stringify({ a: 1, b: undefined, c: 3 })
// Output: '{"a":1,"c":3}'
In arrays, undefined values are replaced with null:
JSON.stringify([1, undefined, 3])
// Output: '[1,null,3]'
This asymmetric behavior is a common source of bugs, especially when round-tripping data through JSON serialization and deserialization.
Common mistakes developers make:
Developers often write {"key": undefined} in JSON files or templates and expect it to work. This produces a parse error because undefined is not a valid JSON token. Another mistake is relying on the presence or absence of a key to convey meaning without documenting the convention. If both {"status": null} and the complete absence of "status" are possible, the API documentation must clarify the semantic difference.
Best practices:
Use null explicitly when you want to indicate that a field exists but has no value. Omit the key when the field is not applicable or not part of the response. Document your convention so consumers know how to interpret both cases. In TypeScript, represent these fields as fieldName: string | null for nullable values or fieldName?: string for optional values.
Use Case
Designing a user profile API response where optional fields like middleName are set to null when not provided, clearly distinguishing between missing data and absent fields.