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

javascript
Published on December 16, 2019

The nullish coalescing operator (??) can be used to give default values to variables in Javascript if they are 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 works in Firefox, Chrome & Edge. Safari is yet to implement it.

Related Tutorials
Getting Property Value in a Deeply Nested Object (using ES2020 Optional Chaining Operator)
Comments
Loading Comments