?? operator in JavaScript

Discussions about the development and maturation of the platform code (UXP).
Warning: may contain highly-technical topics.

Moderators: trava90, athenian200

User avatar
UCyborg
Fanatic
Fanatic
Posts: 171
Joined: 2019-01-10, 09:37

?? operator in JavaScript

Unread 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
Fanatic
Fanatic
Posts: 122
Joined: 2015-06-12, 14:59
Location: Uruguay

Re: ?? operator in JavaScript

Unread 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
Moon Magic practitioner
Moon Magic practitioner
Posts: 2183
Joined: 2018-05-05, 13:29

Re: ?? operator in JavaScript

Unread 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
Fanatic
Fanatic
Posts: 171
Joined: 2019-01-10, 09:37

Re: ?? operator in JavaScript

Unread 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.

Locked