Nullish Coalescing Operator in JavaScript
This article explains the Nullish Coalescing Operator in JavaScript.
YouTube Video
Nullish Coalescing Operator in JavaScript
In JavaScript, the Nullish Coalescing Operator (??
) evaluates whether a value is null
or undefined
and returns a different default value if so. It is similar to the commonly used logical OR operator (||
), but differs in that it specializes in null
and undefined
.
The logical OR operator returns the right-hand value if the left-hand value is falsy
, whereas the nullish coalescing operator returns the right-hand value only when the left-hand value is null
or undefined
. This feature allows correct handling of values like 0
and empty strings (""
).
Basic Syntax
1let result = value ?? defaultValue;
value
is the value being checked.defaultValue
is the value returned whenvalue
isnull
orundefined
.
Examples of Using the Nullish Coalescing Operator
The following example implements a process to return a default value in case of null
or undefined
.
1let name = null;
2let defaultName = "Anonymous";
3
4// If name is null or undefined, 'Anonymous' is returned
5let displayName = name ?? defaultName;
6console.log(displayName); // "Anonymous"
In this code, since name
is null
, the value of defaultName
, "Anonymous"
, is returned. If name
is a value other than null
or undefined
, that value is returned.
Differences with the Logical OR Operator
The nullish coalescing operator is similar to the logical OR operator but has an important difference. The logical OR operator checks for 'falsy' values (false
, 0
, NaN
, ""
, null
, undefined
, etc.), whereas the nullish coalescing operator checks only for null
and undefined
.
Example of Logical OR Operator:
1let count = 0;
2let defaultCount = 10;
3
4// Since count is falsy (0), defaultCount is returned
5let result = count || defaultCount;
6console.log(result); // 10
Example of Nullish Coalescing Operator:
1let count = 0;
2let defaultCount = 10;
3
4// Since count is neither null nor undefined, count is returned as is
5let result = count ?? defaultCount;
6console.log(result); // 0
In this way, the nullish coalescing operator retains valid values such as 0
and empty strings (""
) and returns a default value only when necessary. Since the logical OR operator treats these values as falsy
and returns the default value, it is important to choose the appropriate operator depending on the use case.
Example When Used in Combination:
The nullish coalescing operator can also be combined with other logical operators, but caution is required when doing so.
1let a = null;
2let b = 0;
3let c = false;
4
5// SyntaxError
6let result = a ?? b || c;
- For example, when using it together with the logical OR operator (
||
) or the logical AND operator (&&
), parentheses should be used to clarify the order of operations.
1let a = null;
2let b = 0;
3let c = false;
4
5let result = (a ?? b) || c;
6console.log(result); // false
- In this example,
a ?? b
is evaluated first, and sincea
isnull
,b
is returned. Then,b || c
is evaluated, and sinceb
is falsy,c
is finally returned.
Cases where the nullish coalescing operator is useful
The following are cases where the nullish coalescing operator is useful.
- Default Values for Forms This can be used in scenarios where a default value is set for form input fields when the user does not input anything.
1let userAge = null;
2let defaultAge = 18;
3let age = userAge ?? defaultAge;
4console.log(age); // 18
- API Response Handling
Fallback processing can be performed when the value is
null
orundefined
in responses from the API.
1let apiResponse = {
2 title: "New Article",
3 description: null
4};
5
6let title = apiResponse.title ?? "Untitled";
7let description = apiResponse.description ?? "No description available";
8console.log(title); // "New Article"
9console.log(description); // "No description available"
Summary
The nullish coalescing operator (??
) is very useful for initializing data and handling API responses, as it returns a default value when encountering null
or undefined
. In particular, it is a better choice than the traditional logical OR operator (||
) when you want to properly handle falsy
values such as 0
or empty strings.
About the Nullish Coalescing Assignment Operator (??=)
Overview
In JavaScript, the Nullish Coalescing Assignment Operator ??=
has been introduced to efficiently assign a new value to variables that hold null
or undefined
. This operator is a convenient shortcut for assigning to a variable only if a specific value is null
or undefined
.
Basic Usage
The nullish coalescing assignment operator works as follows:.
- If a variable is
null
orundefined
, it assigns the right-hand side value. - If the variable is neither
null
norundefined
, it does nothing and retains the current value.
Syntax
The basic syntax of the nullish coalescing assignment operator is as follows:.
1x ??= y;
y
is assigned tox
ifx
isnull
orundefined
.- If
x
already has a value (notnull
orundefined
),x
's value will not be changed.
Example
Let's look at a basic example of the nullish coalescing assignment operator.
1let userName = null;
2let defaultName = "Guest";
3
4// Since userName is null, defaultName is assigned
5userName ??= defaultName;
6
7console.log(userName); // "Guest"
- In this code, since
userName
isnull
, the value ofdefaultName
is being assigned.
Next, here's an example where the value is neither null
nor undefined
.
1let userName = "Alice";
2let defaultName = "Guest";
3
4// Since userName is "Alice", nothing is assigned
5userName ??= defaultName;
6
7console.log(userName); // "Alice"
- In this case, since
"Alice"
is already set foruserName
, no assignment is made.
Comparison with other assignment operators
JavaScript has several other assignment operators as well. In particular, the difference with the logical OR assignment operator (||=
) is important.
1let value = 0;
2value ||= 10; // Assign 10 if value is falsy
3console.log(value); // 10
The logical OR assignment operator assigns a value even when encountering falsy
values such as false
, 0
, or an empty string (""
), whereas the nullish coalescing assignment operator only operates when the value is null
or undefined
.
1let value = 0;
2value ??= 10;
3// Since value is neither null nor undefined,
4// nothing is assigned
5console.log(value); // 0
Since the nullish coalescing assignment operator only operates on null
or undefined
, it is very useful when you want to retain values like 0
or false
.
Real-world use cases
A real-world use case for the null coalescing assignment operator can be as follows:.
-
Setting default values
It is useful for setting default values when user input or API responses can be
null
orundefined
.
1let userSettings = {
2 theme: null,
3 notifications: true
4};
5
6// Since theme is null, "light" is assigned
7userSettings.theme ??= "light";
8
9console.log(userSettings.theme); // "light"
-
Handling optional parameters
It can also be utilized to perform default actions when function arguments are not specified.
1function greet(name) {
2 name ??= "Guest";
3 console.log(`Hello, ${name}!`);
4}
5
6greet(); // "Hello, Guest!"
7greet("Alice"); // "Hello, Alice!"
Summary
The nullish coalescing assignment operator (??=
) only assigns a value when the left-hand value is null
or undefined
, making code more concise and helping to prevent unintended assignments. Especially when dealing with "falsy" values like 0
or false
, it can be more appropriate than the traditional logical OR operator (||=
).
By utilizing this operator, you can create more robust and readable code.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.