Nullish Value
May 20, 2023
The term nullish value
refers to a special type of value in JavaScript that has a specific meaning when used in certain contexts. Specifically, a nullish value
is any value that is null
or undefined
. This term is used in situations where a value may or may not be present, and it is important to distinguish between the absence of a value and the presence of a value that is considered “falsy” (e.g. 0
, ''
, false
, etc.).
Purpose
The purpose of the nullish value
concept is to provide a way to check for the absence of a value without mistakenly treating a falsy value as equivalent to a null or undefined value. This is important because there are many situations in which a falsy value is a valid input, but should not be treated as equivalent to a missing or undefined value.
For example, consider a function that takes a number as an argument and returns the square of that number. If the function is called with no argument, it should return 0
, not null
or undefined
. However, if the function is called with the argument 0
, it should return 0
, not null
or undefined
. Without the concept of a nullish value
, it would be difficult to distinguish between these two cases.
Usage
The nullish value
concept is most commonly used in conditional statements and expressions, where it is important to distinguish between the absence of a value and the presence of a falsy value.
For example, consider the following code:
let x = null || 0;
console.log(x);
In this code, the ||
operator is used to set the value of x
to the first non-falsy value in the expression null || 0
. Since null
is falsy, the value of x
will be 0
. However, if we want to check if x
is null or undefined, we cannot use the ||
operator, because it will treat 0
as a valid value. Instead, we can use the ??
operator, which only considers nullish values:
let x = null ?? 0;
console.log(x);
In this code, the ??
operator is used to set the value of x
to the first nullish value in the expression null ?? 0
. Since null
is nullish, the value of x
will be null
.
The ??
operator is also useful when combining multiple values, such as in the following code:
let x = null;
let y = x ?? 0;
console.log(y);
In this code, the value of y
will be 0
, because x
is nullish.