null and undefined
null
is a language keyword
that evaluates to a special value that is usually used to indicate the
absence of a value. Using the typeof
operator on null
returns the string “object”, indicating
that null
can be thought of as a
special object value that indicates “no object”. In practice, however,
null
is typically regarded as the
sole member of its own type, and it can be used to indicate “no value”
for numbers and strings as well as objects. Most programming languages
have an equivalent to JavaScript’s null
: you may be familiar with it as
null
or nil
.
JavaScript also has a second value that indicates absence of
value. The undefined value represents a deeper kind of absence. It is
the value of variables that have not been initialized and the value
you get when you query the value of an object property or array
element that does not exist. The undefined value is also returned by
functions that have no return value, and the value of function
parameters for which no argument is supplied. undefined
is a predefined global variable
(not a language keyword like null
)
that is initialized to the undefined value. In ECMAScript 3, undefined
is a read/write variable, and it
can be set to any value. This error is corrected in ECMAScript 5 and
undefined
is
read-only in that version of the language. If you apply the typeof
operator to the undefined value, it
returns “undefined”, indicating that this value is the sole member of
a special type.
Despite these differences, null
and ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.