JS: Null Coalescing equivalent in JavaScript | JavaScript

Null Coalescing equivalent

Null-Coalescing Operators ?? available in C#, allow the user to return alternate value if the first operator is null

Null-Coalescing Operators ?? available in C#, allow the user to return alternate value if the first operator is null. Null-Coalescing Operators (??) functionality can be achieved with || in JavaScript

Achieving ?? operation in JavaScript

var x = null; var y = 3; var z = x || y;

Demerits of Null-Coalescing with || in JavaScript

In JavaScript, || acts as OR operator, since || is a conditional operator and returns the next operand (value) when first fails.

In case, if the first operand is falsy i.e. (zero 0,empty string "", false, null, undefined, NaN etc.), instead of returning first operand (value) returns the second. Please have a look at falsy chapter of the JavaScript tutorial.

If the code expect other falsy values, then replacing the following line may work as required.

var z = x === null ? y : x;

Summary

  1. For older JavaScript versions, || may work as ?? of C# for with some limitations
  2. || Falsy expressions may cause buggy code, need for write code carefully

As newer version of JavaScript support?? operator, so have a look at null coalescing operator of JavaScript tutorial.