The nullish coalescing operator (??) is a logical operator that allows you to provide a default value when an expression is null or undefined.
This operator, introduced in ECMAScript 2020 (ES11), provides a more precise and clear way to handle null and undefined values (compared to other traditional approaches like using ||).
The nullish coalescing operator is very useful for simplifying and improving the readability of code when working with values that contain null or undefined.
Coalescence is a term that refers to the process of merging or fusing two or more elements into one.
Syntax of the Nullish Coalescing Operator
The syntax of the nullish coalescing operator is simple:
let result = value1 ?? value2;
In this case,
- If
value1is notnullorundefined,resultwill take the value ofvalue1. - If
value1isnullorundefined,resultwill take the value ofvalue2.
For example, in this case
let username = user.name ?? 'No idea, mate';
console.log(username); // 'No idea, mate'
Here,
- If the user’s name were
Pedro,usernamewould bePedro. - Therefore,
usernametakes the value ‘No idea, sir’.
Combination with Other Operators
The ?? operator fits wonderfully well (❤️) with other operators like the optional chaining operator ?..
let username = user?.name ?? 'Unknown';
console.log(username); // 'Unknown'
In this case, username will be ‘No idea, sir’ both if,
userisnulluseris notnull, but itsnameproperty isnull
In the previous example, without ?., if user had been null it would have thrown an exception.
