Chapter 14. Null
Conceptual Overview of Using the null Value
You can use null
to explicitly
indicate that an object property does not contain a value. Typically, if a
property is set up to contain a value, but the value is not available for
some reason, the value null
should be
used to indicate that the reference property has an empty value.
<!DOCTYPE html><html lang="en"><body><script> // the property foo is waiting for a value, so we set its initial value to null var myObjectObject = {foo: null}; console.log(myObjectObject.foo); //logs 'null' </script></body></html>
Note
Donât confuse null
with
undefined
.
undefined
is used by JavaScript to tell you that
something is missing. null
is provided so you can
determine when a value is expected but just not available yet.
typeof Returns null Values as âobjectâ
For a variable that has a value of null
, the typeof
operator returns
'object'
. If you need to verify a null
value, the ideal solution would be to see
if the value you are after is equal to null
. Below, we use the ===
operator to specifically verify that we are
dealing with a null
value.
<!DOCTYPE html><html lang="en"><body><script> var myObject = null; console.log(typeof myObject); // logs 'object', not exactly helpful console.log(myObject === null); // logs true, only for a real null value </script></body></html>
Note
When verifying a null
value,
always use ===
because ==
does not distinguish between null
and undefined
.
Get JavaScript Enlightenment 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.