Original address: Everything about null in JavaScript
Original author: Dmitri Pavlutin
Translator: Gopal
JavaScript
There are two types: primitive ( strings, booleans, numbers, symbols
) and object
An object is a complex data structure. The simplest JavaScript
objects are ordinary objects -- collections of keys and associated values
let myObject = {
name: 'Eric Cartman'
};
But in many cases an object cannot be created. In this case, JavaScript
provides a special value null
indicating that the object is missing
let myObject = null;
In this article, you will learn everything about JavaScript
in null
: what it means, how to detect it, null
and undefined
The difference between undefined
, and why a lot of use null
will make code maintenance difficult, etc.
1. The concept of null
JavaScript
Described in the specification null
null is a primitive type that intentionally does not contain any object value
If you see null
(assigned to a variable or returned by a function), there should have been an object at that location, but for some reason an object was not created
For example, the function greetObject()
creates an object, but can also return null
if the object cannot be created:
function greetObject(who) {
if (!who) {
return null;
}
return { message: `Hello, ${who}!` };
}
greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject(); // => null
When a string parameter is passed in the above function, as expected, the function returns an object { message: 'Hello, Eric!' }
However, when no parameter is passed in the function, the function returns null
. Returning null
is reasonable because the who
parameter has no value, resulting in the greeting
object cannot be created
1.1 A more apt metaphor for null
Consider a more apt analogy about null
where you can think of a variable as a box. Just like variables can hold objects, boxes can hold items like teapots etc.
But once you receive a box, open it, there is nothing! Someone made a mistake and gave you an empty box. The box contains nothing, or in other words, it contains a null
value
2. How to detect null
Check null
good way is to use strict equality operator
const missingObject = null;
const existingObject = { message: 'Hello!' };
missingObject === null; // => true
existingObject === null; // => false
The result of ---c705fac15278c48a22a49ebb01fe17af missingObject === null
is true
because the missingObject
variable contains a null
value. If the variable contains a non-null value, such as an object, the expression existingObject === null
results in false
2.1 null is a false value
null
与false
、0、"、 undefined
、 NaN
假值。如果在条件语句中遇到它们,那么JavaScript
will force them to false
Boolean(null); // => false
if (null) {
console.log('null is truthy');
} else {
console.log('null is falsy'); // logs 'null is falsy'
}
2.2 typeofnull
typeof value
The type operator can determine the type of a value. For example, a type of 15 is number
, typeof { prop: 'Value' }
is equal to object
.
Interestingly, what is the result of null
value type
typeof null; // => 'object'
How can a missing object type be judged as object
? It turns out typoef null
as object
is a bug in the early JavaScript
implementation of ---0146cebf4895589c08
Do not use the typeof
operator detection null
value. Use the strict equality operator myVar === null
as mentioned before
If you want to use typeof
to check if a variable is an object, you must exclude the case of null
function isObject(object) {
return typeof object === 'object' && object !== null;
}
isObject({ prop: 'Value' }); // => true
isObject(15); // => false
isObject(null); // => false
3. The Null Trap
null
usually occurs unexpectedly when you expect to use an object. Then, if you try to extract properties from null
, JavaScript
will throw an error
Let's use the greetObject()
function again and try to access the message
property from the returned object
let who = '';
greetObject(who).message;
// throws "TypeError: greetObject() is null"
Because the who
variable is an empty string, the function returns null
. When accessing the message
property from null
, a TypeError error is thrown
You can handle this by using the optional chaining operator null
let who = '';
greetObject(who)?.message ?? 'Hello, Stranger!';
// => 'Hello, Stranger!'
Or use the two options described in the next section.
4. Alternatives to null
It's easy to return null
when you can't construct an object. But this approach also has disadvantages
Once null
appears in the execution stack, you always have to check it
We try to avoid returning null
:
- Return the default object instead of
null
- throw an error instead of returning
null
Let's recall greetObject()
function returns greeting
object
A default object can be returned instead of null
when arguments are missing
function greetObject(who) {
if (!who) {
who = 'Stranger';
}
return { message: `Hello, ${who}!` };
}
greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject(); // => { message: 'Hello, Stranger!' }
or throw an error
function greetObject(who) {
if (!who) {
throw new Error('"who" argument is missing');
}
return { message: `Hello, ${who}!` };
}
greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject(); // => throws an error
These practices will allow you to avoid dealing entirely null
5. null vs undefined
undefined
is the value of an uninitialized variable or object property
For example, if a variable is declared without an initial value, the result of accessing the variable is undefined
let myVariable;
myVariable; // => undefined
The main difference between null
and undefined
is that null
undefined
The strict equality operator === distinguishes between null
and undefined
null === undefined; // => false
The loose equality operator ==
considers null
and undefined
equal
null == undefined; // => true
I use the loose equality operator to check if the variable is null
or undefined
function isEmpty(value) {
return value == null;
}
isEmpty(42); // => false
isEmpty({ prop: 'Value' }); // => false
isEmpty(null); // => true
isEmpty(undefined); // => true
6. Summary
null
is a special value in JavaScript
representing the missing object
The strict equality operator determines whether a variable is empty: variable === null
.
typoef
operator is used to determine the type of the variable ( number, string, boolean
). However, typeof
is misleading in the case of null
b77bfd616cf48084037670ed2f25be71---: typeof null
results in object
null
and undefined
are equivalent to some extent, but null
means a missing object, while undefined
state
Avoid returning null
as much as possible or set the variable to null
. Because this practice will lead to the expansion of the null
value and the need to verify the null
. Instead, it would be better practice to try to use an object with default properties, or even throw an error
What method would you use to check null
?
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。