JavaScript: Special case of undefined when using JSON parse and stringify
1 min read

JavaScript: Special case of undefined when using JSON parse and stringify

JSON spec does not allow undefined but allows null. This gives several special cases.

JSON.stringify([1, undefined, 2]) // prints '[1,null,2]'

What will happen if we have an object with an undefined property? That property will be ignored by default.

JSON.stringify({name: undefined}) // prints '{}'

To include undefined properties, we need to utilize the replacer function.

JSON.stringify({name: undefined}, (k, v) => v === undefined ? null : v) // prints '{"name":null}'