Many programming languages have one “non-value” called
null. It indicates that a variable does not currently point to an object. For example, when it hasn’t been initialized, yet.
Both values are very similar and often used interchangeably. How they differ is therefore subtle. The language itself makes the following distinction:
undefinedmeans “not initialized” (e.g. a variable) or “not existing” (e.g. a property of an object).
nullmeans “the intentional absence of any object value” (a quote from the language specification).
Programmers may make the following distinction:
undefinedis the non-value used by the language (when something is uninitialized etc.).
nullmeans “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.
The following subsections describe where
null appear in the language. We’ll encounter several mechanisms that are explained in more detail later in this book.
x is not provided:
.unknownProp is missing:
If you don’t explicitly specify the result of a function via a
undefined for you:
The prototype of an object is either an object or, at the end of a chain of prototypes,
Object.prototype 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):
The JSON data format does not support
Checking for either:
x have a value?
Truthy means “is
true if coerced to boolean”. Falsy means “is
false if coerced to boolean”. Both concepts are explained properly in §14.2 “Falsy and truthy values”.
nulldon’t have properties
.foo and returns the result.
If we apply
getFoo() to various value, we can see that it only fails for
intvariables are initialized with
See quiz app.