DEV Community

loading...
JS Mates

Why the undefined variable is not sent in a JSON API response?

Paramanantham Harrison
Originally published at jsmates.com on ・1 min read

What will happen if some of your variables is undefined in the JSON response?

It will be removed from the response by most server framework. Because

Undefined is not a valid JSON type. All javascript objects are not valid JSON and vice versa.

Example,

const response = {
  undefined: undefined,
  null: null,
  true: true,
  false: false,
  number: 0,
  string: 'string'
};

res.json(response);
Enter fullscreen mode Exit fullscreen mode

The response will be,

{ "null": null, "true": true, "false": false, "number": 0, "string": "string" }
Enter fullscreen mode Exit fullscreen mode

All other values will be sent to the response but undefined won't be sent.

You can see it in action here,

Discussion (0)