The nullish coalescing operator
Let’s assume that the result of
valueA ?? valueB is:
valueAif it’s not
result = valueA ?? valueB is a short equivalent to:
result = (valueA !== null && valueA !== undefined) ? valueA : valueB;
let firstName = null; let lastName = undefined; let nickName = "panayiotisgeorgiou"; alert(firstName ?? lastName ?? nickName ?? "Anonymous"); //show the first not-null/undefined variable Result panayiotisgeorgiou
- The ?? operator is used to check null values and you can also assign a default value to a variable whose value is null(or nullable type).
- You are not allowed to overload ?? operator.
- It is right-associative.
- In ?? operator, you can use throw expression as a right-hand operand of ?? operator which makes your code more concise.
At the time of this writing, it looks like the latest versions of Chrome, Firefox, Edge, and Safari are good with the nullish coalescing operator.
That’s it for now. 😉
If you liked this article, then please subscribe to my YouTube Channel for video tutorials.