Is There a "Null Coalescing" Operator in JavaScript

Is there a null coalescing operator in JavaScript?

Update

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

Old Answer

Please check compatibility before using it.


The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!";

There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.



Clarification

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

This means:

var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"

How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?

The || operator evaluates to the right-hand side if and only if the left-hand side is a falsy value.

The ?? operator (null coalescing) evaluates to the right-hand side if and only if the left-hand side is either null or undefined.

false, 0, NaN, "" (empty string) are for example considered falsy, but maybe you actually want those values. In that case, the ?? operator is the right operator to use.

When should I use ?? (nullish coalescing) vs || (logical OR)?

The OR operator || uses the right value if left is falsy, while the nullish coalescing operator ?? uses the right value if left is null or undefined.

These operators are often used to provide a default value if the first one is missing.

But the OR operator || can be problematic if your left value might contain "" or 0 or false (because these are falsy values):

console.log(12 || "not found") // 12
console.log(0 || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log("" || "not found") // "not found"

console.log(true || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null || "not found") // "not found"

In many cases, you might only want the right value if left is null or undefined. That's what the nullish coalescing operator ?? is for:

console.log(12 ?? "not found") // 12
console.log(0 ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log("" ?? "not found") // ""

console.log(true ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null ?? "not found") // "not found"

While the ?? operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:

The ?? operator was added to TypeScript 3.7 back in November 2019.

And more recently, the ?? operator was included in ES2020, which is supported by Node 14 (released in April 2020).

When the nullish coalescing operator ?? is supported, I typically use it instead of the OR operator || (unless there's a good reason not to).

Why does JavaScript's null coalescing operator (||) not work with es6 variables (let/const)?

Why does var APP = APP || {}; work fine, but const APP = APP || {}; not?

Lets clarify how these statements are evaluated. Before any code is executed, the runtime finds all variable declarations and creates an entry for each in the current scope. Some time later when APP = APP || {} is executed, the value of APP is read before it was ever assigned value.

It "works" with var, because var declarations are implicitly initialized with the value undefined. Therefore accessing the variable before a value is assigned to it returns undefined.

const and let declarations however are left uninitialized. You cannot access them before they have been assigned the value from their initial declaration. This is also known as temporal dead zone or TDZ for short.

Here is a simplified example:

console.log(foo); // undefined

var foo = 42;

console.log(foo); // 42

Nullish Coalescing operator in JavaScript

For now you have to do this like:

(this.state.updateItem || {}).unit || 'Unit'

There is a stage one proposal to ES (JavaScript) for optional chaining whereby we'll (eventually, hopefully) be able do do something like this:

this.state.updateItem?.unit || 'Unit'

And if you're doing babel you can use it now!:

https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

Edit: The proposal is now in stage 4 (as of January 2020) and will be added into the JavaScript standard

Opposite of nullish coalescing operator

To my knowledge, there is no such operator and also no proposal to add one. Instead you can rely on the standard way to check for nullish values: b == null

a = b == null ? b : func(b)

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

You can use the logical 'OR' operator in place of the Elvis operator:

For example displayname = user.name || "Anonymous" .

But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.

For example The Existential Operator

zip = lottery.drawWinner?().address?.zipcode

Function shortcuts

()->  // equivalent to function(){}

Sexy function calling

func 'arg1','arg2' // equivalent to func('arg1','arg2')

There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>' but it adds a lot of functionality :) . Using <script type='text/coffeescript'> is really only intended for development and not production.

What does ?. and ?? mean in javascript

1. Optional chaining (?.)

From MDN said that

The optional chaining operator (?.) permits reading the value of a
property located deep within a chain of connected objects without
having to expressly validate that each reference in the chain is
valid.

The ?. operator functions similarly to the . chaining operator, except
that instead of causing an error if a reference is nullish (null or
undefined)
, the expression short-circuits with a return value of
undefined. When used with function calls, it returns undefined if the
given function does not exist.

const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};

console.log(adventurer.dog?.name); // expected output: undefined

console.log(adventurer.dog.name); // Thow an error message like
//`"message": "Uncaught TypeError: Cannot read property 'name' of undefined",`


Related Topics



Leave a reply



Submit