JavaScript undefined and null: Missing Values
Quick answer
undefined and null are two distinct primitive values. Undefined often represents a value that has not been supplied; null is commonly chosen to represent an explicitly absent result. The meanings in an application are conventions that should be documented.
How it works
A let declaration without an initializer obtains undefined when executed. A function that reaches the end without returning a value also returns undefined. The literal null must be written explicitly when that is your intended value. Neither means zero or an empty string. The strict equality operator === (preview) compares without converting types.
let result;console.log(result);result = null;console.log(result);Expected output in Node.js:
undefinednullAssignment makes the choice of null explicit.
function pending() {}console.log(pending() === undefined);console.log(null === undefined);Expected output in Node.js:
truefalseThe two primitive types are different.
Common mistakes
Do not assign a default simply because a value is zero. Zero, false and an empty string can all be legitimate results. Do not confuse an uninitialized lexical binding (TDZ) with undefined.
Practice
Create a function that has no return statement, then a function that returns null. Compare both outputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript undefined and null: Missing Values — Knowledge Check
Apply the taught concept and reason about the result.
What does let value; console.log(value); display after declaration?
Which is a common explicit absence signal selected by application code?
What is the result of null === undefined?
What does function empty() {} return?
Which value might be a valid result rather than absence?