Dev.to WebDev 🛠 Dev 👁 0 📖 1 min read

null and undefined are not the same nothing

null and undefined are not the same thing. In a component API, treating them alike can silently delete a whole feature, with no error and no warning. In our design system, the root prop says where a popup should rende

null and undefined are not the same thing.

In a component API, treating them alike can silently delete a whole feature, with no error and no warning.

In our design system, the root prop says where a popup should render. It carries three intents:

  1. Nothing passed: inherit from the nearest PortalProvider.
  2. null passed: ignore the provider and use document.body.
  3. An element or a ref passed: use exactly that.

The obvious code would be root ?? portalRoot. It looks right, but ?? treats null and undefined the same way. Case 2 falls through to the fallback and the escape hatch is gone.

The final version compares against undefined explicitly:

if (root === undefined) return portalRoot;
return root;

What I take from this to any API:

  • undefined means "I didn't say". It's what React hands you when a prop is omitted, and it's the only value that triggers a default parameter.
  • null means "I said: nothing". It's a decision by the caller.
  • If the difference matters, it needs one test per case. Ours has one for an omitted prop, one for an explicit null and one for an element.

A two-character operator almost removed an entire feature.

In your codebase, do null and undefined mean different things, or do you ban one of them?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.