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 nullbug —typeof nullreturns"object", a historical bug preserved for backward compatibility since fixing it would break the web. Verified directly:typeof undefinedcorrectly returns"undefined", buttypeof nulldoes not return"null". - A precise answer names
null + 1(which is1, sinceNumber(null)is0) versusundefined + 1(which isNaN, sinceNumber(undefined)isNaN) — verified directly, a real, sharp distinction in numeric coercion. - A precise answer names
JSON.stringifybehavior: a property with valueundefinedis genuinely dropped from the output entirely, while a property with valuenullis kept — verified directly. This is a real, practical reason APIs often usenulloverundefinedfor "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.