Use-Cases of this tutorial
- Know how to set default values to variables if they are null or defined.
- Know about the Nullish Coalescing Operator (??)
The nullish coalescing operator (??) can be used to give default values if a variable is either null or undefined.
A common practice in programming is to give default values to variables if they are either undefined or null.
// a is undefined var a; var test = a ?? 100; // "100" console.log(test);
var a = 34; var test = a ?? 100; // "34" console.log(test);
// c does not exist var test = c ?? 100; // "100" console.log(test);
If the left side expression is either null or undefined, then ?? operator returns the result of the right side expression. If not, then the left side expression is returned.
Nullish coalescing operator arrives in Firefox 72. Other browsers are yet to implement it.