Is there a null coalescence operator in javascript? Like the operator ?? of the C#

Question:

In C# there is an operator ?? which serves to make null coalescence, used following the syntax:

var valor = valorAnulável ?? valorPadrão;

Where:

  • NullableValue is any value including null

  • defaultValue is any value, usually not null

The operator returns NullableValue if it is not null, and if it is null, returns the DefaultValue. It's the same as saying:

var valor = valorAnulável != null ? valorAnulável : valorPadrão;

Is there anything like this in Javascript?

Answer:

Is it possible to get a behavior similar to the operator ?? from C# in javascript, using the logical or operator : || .

There are, however, some differences, and for that we have to understand what the || of javascript means.

var resultado = valorA || valorB;

is exactly the same as:

var resultado = valorA ? valorA : valorB;

It turns out that in javascript, practically all values ​​can be treated in a logical way, that is, converted to true or false. As for the previous operation, when the value valorA is treated as true, the result of the expression is its own value. When treated as false, the result of the expression is the value valorB .

We must then understand what is treated as true and false.

What is false:

  • empty string: ""
  • number 0 (zero)
  • false
  • null
  • undefined
  • NaN

What is true:

  • everything that isn't fake… including the following
  • non-empty strings: "0", "true", "false" (important to remember this one)
  • all numbers other than 0: 1, -1, -1000, 1/10
  • true

Some examples

false || "texto qualquer"     // "texto qualquer"
"" || "texto qualquer"        // "texto qualquer"
0 || "texto qualquer"         // "texto qualquer"
null || "texto qualquer"      // "texto qualquer"
undefined || "texto qualquer" // "texto qualquer"

"algum texto" || "texto qualquer" // "algum texto"
1 || "texto qualquer"             // 1

Noticed the difference to the ?? from C#… only if the first is null will the second be the result, otherwise the result is the first. Unlike javascript where the second is the result, if the value of the first is falso , 0 or "" .

Scroll to Top