Nullish Coalescing Operator in TypeScript
In this article, we will explain the Nullish Coalescing Operator in TypeScript.
YouTube Video
Nullish Coalescing Operator in TypeScript
The nullish coalescing operator (??
) in TypeScript is similar to JavaScript's short-circuit evaluation but is more explicitly used to provide a fallback value only when the left-hand side is null
or undefined
. This operator allows you to easily check if a value is null
or undefined
and set a default value as needed.
The nullish coalescing operator (??
) returns the right-hand value only if the left-hand side is null
or undefined
. This allows values like false
, an empty string, or the number 0
to be evaluated as they are. This is a major difference from the traditional logical OR operator (||
). This operator was introduced in TypeScript 3.7.
Basic Syntax
The basic syntax is as follows:.
1let result = value ?? defaultValue;
value
is the target being checked fornull
orundefined
.defaultValue
is the value returned whenvalue
isnull
orundefined
.
Example Usage
1function getUserName(userName: string | null | undefined): string {
2 return userName ?? "Default User";
3}
4
5console.log(getUserName("Alice")); // Output: Alice
6console.log(getUserName(null)); // Output: Default User
7console.log(getUserName(undefined)); // Output: Default User
Here, the function getUserName
returns "Default User"
if userName
is null
or undefined
, otherwise it returns the value of userName
.
Difference from the logical OR operator
There is an important difference between the nullish coalescing operator and the logical OR operator. The logical OR operator treats values like false
, 0
, and ""
(empty string) as "falsy," just like null
and undefined
. On the other hand, the nullish coalescing operator only uses null
and undefined
for fallback.
Example of the logical OR operator
1function getUserAge(age: number | null | undefined): number {
2 return age || 18; // `0` also applies the default value
3}
4
5console.log(getUserAge(25)); // Output: 25
6console.log(getUserAge(0)); // Output: 18
7console.log(getUserAge(null)); // Output: 18
- As shown, the logical OR operator returns the default value
18
even when the value is0
.
Example of the nullish coalescing operator
1function getUserAge(age: number | null | undefined): number {
2 return age ?? 18; // `0` does not apply the default value
3}
4
5console.log(getUserAge(25)); // Output: 25
6console.log(getUserAge(0)); // Output: 0
7console.log(getUserAge(null)); // Output: 18
-
On the other hand, the nullish coalescing operator returns the original value even when it is
0
. -
The choice between the logical OR operator and the nullish coalescing operator depends on whether
0
or an empty string is acceptable. For example, if you want to keep a user's age as0
, you need to use the nullish coalescing operator.
Combination with Types
You can enhance the robustness of your code by leveraging TypeScript's type safety in combination with the nullish coalescing operator. In the following example, default values are used when certain properties are null
or undefined
.
1interface User {
2 name: string;
3 age?: number | null;
4}
5
6function displayUserInfo(user: User): string {
7 const userName: string = user.name;
8 const userAge: number = user.age ?? 18;
9 return `Name: ${userName}, Age: ${userAge}`;
10}
11
12const user1: User = { name: "John", age: null };
13const user2: User = { name: "Doe" };
14
15console.log(displayUserInfo(user1)); // Output: Name: John, Age: 18
16console.log(displayUserInfo(user2)); // Output: Name: Doe, Age: 18
- In the
User
interface, theage
property can be anumber
,null
, orundefined
, so the nullish coalescing operator is used to assign a default value of18
. - Meanwhile, the
name
property only allowsstring
, so the value is used as is.
Summary
- The nullish coalescing operator helps set a default value only when the value is
null
orundefined
. Unlike the traditional logical OR operator, it does not treatfalse
,0
, or empty strings as 'falsy', making it especially useful when you want to preserve those values. Additionally, combining it with TypeScript's type system allows for creating more robust and readable code. - By effectively using the nullish coalescing operator, you can concisely write logic for setting default values while reducing unnecessary
null
checks.
Nullish Coalescing Assignment Operator in TypeScript
The nullish coalescing assignment operator (??=
) is a relatively new operator introduced in TypeScript, providing a convenient method to assign a value only if the variable is null
or undefined
. Here, we will explain how this operator works, in what situations it is effective, and provide examples with code.
What is the Nullish Coalescing Assignment Operator
The nullish coalescing assignment operator is an assignment operator based on the nullish coalescing operator. This operator is used to assign a new value only if the variable is null
or undefined
.
1let variable: string | null = null;
2variable ??= "Default Value"; // The variable is null,
3 // so the new value is assigned
4
5console.log(variable); // Output: "Default Value"
By using this operator, you can more concisely write the logic of "assign if the variable is undefined or null".
Comparison with Traditional Assignment Methods
Without the nullish coalescing assignment operator, you would need to use an if
statement or a ternary operator to achieve the same behavior. Let's compare with the traditional assignment methods.
Conventional method
Using an if
statement, it can be written as follows:.
1let variable: string | null | undefined = null;
2if (variable === null || variable === undefined) {
3 variable = "Default Value";
4}
5console.log(variable); // Output: "Default Value"
Method using the ternary operator
Alternatively, using the ternary operator, it can be written as follows:.
1let variable: string | null | undefined = undefined;
2variable = variable != null ? variable : "Default Value";
3// != null checks for both null and undefined
4// (intentional loose equality comparison)
5
6console.log(variable); // Output: "Default Value"
A concise method using the nullish coalescing assignment operator
On the other hand, using the nullish coalescing assignment operator, it can be written like this:.
1let variable: string | null = null;
2variable ??= "Default Value";
3console.log(variable); // Output: "Default Value"
As shown, the nullish coalescing assignment operator is much simpler and more readable compared to other assignment methods, improving code clarity.
Specific Examples of Using ??=
The nullish coalescing assignment operator is useful in various scenarios, such as initializing object properties and setting default values. Here are some specific examples.
Initialization of object properties
1interface Config {
2 theme?: string;
3 language?: string;
4}
5
6let config: Config = {};
7config.theme ??= "light"; // Set the default "light" theme if none is specified
8config.language ??= "en"; // Set the default "en" language if none is specified
9
10console.log(config); // Output: { theme: "light", language: "en" }
Initialization of arrays
1let numbers: number[] | null = null;
2numbers ??= []; // Assign an empty array if numbers is null
3
4numbers.push(1);
5console.log(numbers); // Output: [1]
Setting default values for function arguments
1function greet(name?: string) {
2 name ??= "Guest"; // Set name to "Guest" if it is undefined or null
3 console.log(`Hello, ${name}!`);
4}
5
6greet(); // Output: "Hello, Guest!"
7greet("Alice"); // Output: "Hello, Alice!"
Notes and Constraints
The nullish coalescing assignment operator is very useful, but there are some caveats.
Only null
and undefined
are targeted..
1let str: string | null = "";
2str ??= "Default";
3console.log(str); // Output: "" (remains an empty string)
4
5let num: number | undefined = 0;
6num ??= 100;
7console.log(num); // Output: 0 (remains 0)
- This operator performs assignment only when the value is
null
orundefined
. For example, values like an empty string (""
),0
, orfalse
are not targeted.
Be careful when using it with other operators..
1let value: string | null = null;
2
3// Targets not only "null" and "undefined" but also falsy values
4value ||= "Default";
5console.log(value); // Output: "Default"
6
7value = "";
8// An empty string is also targeted
9value ||= "Default";
10console.log(value); // Output: "Default"
11
12value = null;
13// Targets only null or undefined
14value ??= "Default";
15console.log(value); // Output: "Default"
- The nullish coalescing assignment operator may produce unintended results when used with other operators. It is especially important to understand the difference between it and the logical OR assignment operator.
Sample Code
1let config: { theme?: string; language?: string } = {};
2
3// Use Nullish Coalescing Assignment to set default values
4config.theme ??= "light";
5config.language ??= "en";
6
7console.log(config); // Output: { theme: "light", language: "en" }
8
9let list: number[] | null = null;
10list ??= [];
11list.push(42);
12
13console.log(list); // Output: [42]
- By using the nullish coalescing assignment operator, you can eliminate unnecessary code and write smoother, more elegant TypeScript code.
Summary
The nullish coalescing assignment operator (??=
) is one of the simple and efficient assignment operations in TypeScript. It is particularly useful when you need to perform checks for null
or undefined
while setting default values. Compared to traditional if
statements or ternary operators, the code becomes more concise and readable.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.