I noticed something interesting about JSON.stringify() when dealing with undefined values.
Take this object:
const user = {
name: "Alex",
age: undefined,
active: true
};
console.log(JSON.stringify(user));
The output is:
{"name":"Alex","active":true}
The age property is completely missing.
I originally expected it to be something like "age": null, but that's not how it works.
When JSON.stringify() encounters an undefined value in an object, it skips that property.
But arrays behave differently.
const values = [1, undefined, 3];
console.log(JSON.stringify(values));
// [1,null,3]
Here, undefined becomes null instead of being removed.
I guess that makes sense, since removing an array element would change the positions of everything after it.
There's also a difference between explicitly setting a property to null and leaving it undefined.
const a = { name: undefined };
const b = { name: null };
console.log(JSON.stringify(a)); // {}
console.log(JSON.stringify(b)); // {"name":null}
This is worth remembering when sending JSON data to an API.
For example:
const updates = {
username: "alex",
bio: undefined
};
fetch("/api/profile", {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updates)
});
The request body won't contain bio at all.
Depending on how the API handles partial updates, an omitted field might mean "leave it unchanged", while null could mean "clear this field".
Not every API follows that convention, though.
Anyway, JSON.stringify() is doing what it's supposed to do. It's just easy to forget that JavaScript objects and JSON don't handle undefined in the same way.
Top comments (0)