Skip to the solution
EasyFrontend5 min read

What is the difference between null and undefined?

584 views

The problem

Question presented to candidate: "What's the difference between null and undefined, and when would you deliberately choose to use one over the other in your own code?"

What a strong answer should cover:

  • πŸ“Œ Interview term: undefined β€” the value JavaScript automatically assigns to a variable that has been declared but not yet given a value, to a missing function argument, or to accessing a property that does not exist on an object. It represents an implicit, unintentional absence.
  • πŸ“Œ Interview term: null β€” a value a developer explicitly assigns to represent "no value" or "empty" on purpose. It is an intentional absence, set deliberately by code, not automatically by the engine.
  • πŸ“Œ Interview term: the famous typeof null bug β€” typeof null returns "object", a historical bug preserved for backward compatibility since fixing it would break the web. Verified directly: typeof undefined correctly returns "undefined", but typeof null does not return "null".
  • A precise answer names null + 1 (which is 1, since Number(null) is 0) versus undefined + 1 (which is NaN, since Number(undefined) is NaN) β€” verified directly, a real, sharp distinction in numeric coercion.
  • A precise answer names JSON.stringify behavior: a property with value undefined is genuinely dropped from the output entirely, while a property with value null is kept β€” verified directly. This is a real, practical reason APIs often use null over undefined for "explicitly no value" fields.

Clarifying questions expected:

  • None β€” this is a definitional/comparison question; naming the intentional-vs-implicit distinction plus the coercion/serialization differences is the strong signal.

Code / implementation expected: Optional β€” showing the typeof and JSON.stringify contrasts directly demonstrates real understanding.

  • null
  • undefined

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal typeof, coercion, and JSON.stringify differences between null and undefined

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 19 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is the difference between find and filter?

Continue