Nullish Coalescing Operator??
The || (OR) operator
The || (OR) operator will return the right operand if the left operand is falsy (false, 0, empty string, null, undefined, NaN).
When to use?
Use || when you want to provide a fallback for any "falsy" value.
?? (Nullish Coalescing) operator
The ?? (Nullish Coalescing) operator will only return the right operand if the left operand is null or undefined.
When to use?
Use ?? when you want to provide a default value for null or undefined, but consider 0 and empty strings to be valid values.
Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Assume a function that returns a count indicating number of followers. This could be a social networking app. | |
function getFollowerCount() { | |
return count; // assume could be null, undefined, 0, "". | |
} | |
//1: Using OR operator | |
let followerCount = getFollowerCount() || "not applicable"; // Uses OR, NOT ideal | |
//why? | |
//Here, if age is 0 which is a possible valid value, '', or false, | |
//'followerCount' variable would incorrectly point to value 'not applicalbe'. | |
//2 //1: Using ?? a.k.a null coalescing operator | |
let followerCount = getFollowerCount() ?? "not applicable"; // Uses ??, ideal | |
//why? | |
//The '??' operator provides a default value of 'not applicable' for null/undefined, | |
//but not for falsy values like 0, empty strings, or false. |