Setting Default Values to Variables if null or undefined (using Nullish Coalescing Operator)

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.

The nullish coalescing operator has been introduced in Javascript for these cases. It is represented by ?? (double question mark).

// 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.

Browser Compatibility

Nullish coalescing operator arrives in Firefox 72. Other browsers are yet to implement it.

Loading Comments