?? operator in JavaScript

Discussions about the development and maturation of the Unified XUL Platform (UXP).
Warning: may contain highly-technical topics.

Moderator: trava90

Post Reply
User avatar
UCyborg
Apollo supporter
Apollo supporter
Posts: 48
Joined: 2019-01-10, 09:37

?? operator in JavaScript

Post by UCyborg » 2020-11-22, 01:53

I recently came across some JavaScript code that looks like this:

Code: Select all

let someStringVar = someStringArray[4] ?? '';
Has anyone seen this before? UXP browsers don't seem to support it, but behavior seems the same as if "??" is replaced with "||".

Lurker_01
Moon lover
Moon lover
Posts: 88
Joined: 2015-06-12, 14:59
Location: Uruguay

Re: ?? operator in JavaScript

Post by Lurker_01 » 2020-11-22, 02:27

UCyborg wrote:
2020-11-22, 01:53
I recently came across some JavaScript code that looks like this:

Code: Select all

let someStringVar = someStringArray[4] ?? '';
Has anyone seen this before? UXP browsers don't seem to support it, but behavior seems the same as if "??" is replaced with "||".
This is a https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
At the moment UXP doesn't support complex operators, like this one.
See also similar operator for object properties and Moonchild comment here https://repo.palemoon.org/MoonchildProductions/UXP/issues/1658

vannilla
Board Warrior
Board Warrior
Posts: 1274
Joined: 2018-05-05, 13:29

Re: ?? operator in JavaScript

Post by vannilla » 2020-11-22, 02:30

https://developer.mozilla.org/en-US/doc ... g_operator
Contrary to the logical OR (||) operator, the left operand is returned if it is a falsy value which is not null or undefined. In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples.
It appears to be a big pile of nothing to save a few keystrokes instead of typing

Code: Select all

let foo = (bar === undefined || bar === null) ? baz : bar
which is equally unreadable.

User avatar
UCyborg
Apollo supporter
Apollo supporter
Posts: 48
Joined: 2019-01-10, 09:37

Re: ?? operator in JavaScript

Post by UCyborg » 2020-11-22, 08:35

Thanks, had no idea what it's called and consequently what the difference is compared to logical OR since I didn't find the documentation. Looks like logical OR works just as desired when you're dealing with strings and want to use it to populate the cell in the data table with empty string in the case you got null or undefined value.

Post Reply