Introduction
JavaScript and its superset, TypeScript, provide us with many tools to make our daily development tasks easier and our code more concise. One such tool is the Nullish Coalescing Operator (??
). In this post, I'll walk you through how to use it and why it's so powerful.
What is the Nullish Coalescing Operator?
The Nullish Coalescing Operator (??
) returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand.
Examples of Using the Nullish Coalescing Operator
Here are some examples of using the Nullish Coalescing Operator in JavaScript/TypeScript:
let x = null;
let y = x ?? "default";
console.log(y); // "default"
In this example, x
is null
, so y
becomes "default"
.
Another example:
let x = "Hello, world!";
let y = x ?? "default";
console.log(y); // "Hello, world!"
In this example, x
is not null
or undefined
, so y
becomes x
which is "Hello, world!"
.
Nullish Coalescing Operator vs OR Operator
The OR operator (||
) in JavaScript also behaves similarly, but it returns the right-hand side operand if the left-hand side operand is falsy
(false
, 0
, ""
, null
, undefined
, NaN
). This is an important difference from the Nullish Coalescing Operator. Let's see it in the examples below:
let x = "";
let y = x || "default";
console.log(y); // "default"
In this example, x
is ""
(falsy), so y
becomes "default"
.
But with the Nullish Coalescing Operator:
let x = "";
let y = x ?? "default";
console.log(y); // ""
In this example, x
is not null
or undefined
, so y
becomes x
which is ""
.
So, the Nullish Coalescing Operator is specialized for checking null
or undefined
, allowing us to avoid the problem of the OR operator replacing valid values like 0
or ""
(empty string) with default values.
Conclusion
The Nullish Coalescing Operator (??
) is a powerful tool in JavaScript and TypeScript development. You can use this operator to keep your code concise when setting default values for potentially non-existent values. Also, understanding the difference from the OR operator (||
) allows you to use the Nullish Coalescing Operator more appropriately.
That's all for the tutorial on how to use the Nullish Coalescing Operator in JavaScript/TypeScript. I hope this post helps your development even a little. I'd appreciate it if you could give a like or share. Happy coding!
Top comments (1)
Great article! Iβve been using the nullish coalescing operator for a while now and itβs been a better choice for assigning defaults.