Many programming languages have one “non-value” called . It indicates that a variable does not currently point to an object. For example, when it hasn’t been initialized, yet.
In contrast, JavaScript has two of them: undefined
and null
.
Both values are very similar and often used interchangeably. How they differ is therefore subtle. The language itself makes the following distinction:
undefined
means “not initialized” (e.g. a variable) or “not existing” (e.g. a property of an object).null
means “the intentional absence of any object value” (a quote from ).
Programmers may make the following distinction:undefined
is the non-value used by the language (when something is uninitialized etc.).null
means “explicitly switched off”. That is, it helps implement a type that comprises both meaningful values and a meta-value that stands for “no meaningful value”. Such a type is called option type or maybe type in functional programming.
13.2.1. Occurrences of undefined
Uninitialized variable myVar
:
Parameter x
is not provided:
Property .unknownProp
is missing:
If you don’t explicitly specify the result of a function via the return
operator, JavaScript returns undefined
for you:
13.2.2. Occurrences of null
The prototype of an object is either an object or, at the end of a chain of prototypes, null
. does not have a prototype:
If you match a regular expression (such as /a/
) against a string (such as 'x'
), you either get an object with matching data (if matching was successful) or null
(if matching failed):
Checking for either:
Does x
have a value?
Is x
either undefined
or null
?
Truthy means “is true
if coerced to boolean”. Falsy means “is if coerced to boolean”. Both concepts are explained properly in .
undefined
and null
are the two only JavaScript values where you get an exception if you try to read a property. To explore this phenomenon, let’s use the following function, which reads (“gets”) property .foo
and returns the result.
If we apply getFoo()
to various value, we can see that it only fails for undefined
and null
:
- Variables with object types are initialized with
null
.