DEV Community

Paramanantham Harrison for JS Mates

Posted on • Originally published at jsmates.com on

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

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,

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay