How can I get eslint to accept the nullish-coalescing assignment?

970 views Asked by At

The "nullish-coalescing assignment" operator, ??=, is a relatively recent introduction to JavaScript; but not all that recent... and yet, eslint, even newer versions like 8.38.0, seem not to recognize it - and yields a syntax error about the assignment (the = after the ??). Here's the line I'm trying to get to pass the check:

var ObjectUtils  ??=  ChromeUtils.import("resource://gre/modules/ObjectUtils.jsm").ObjectUtils;

Why is this happening? And - how can I tell eslint to accept this operator?

1

There are 1 answers

9
T.J. Crowder On

You need to make sure ecmaVersion is set to "latest" or to 2021 (aka 12) or higher, so ESLint knows what version of JavaScript to parse (more in the configuration help). Here's an ESLint playground example using ??= successfully with the version set to "latest"; here's one where it doesn't work because the version is set to 2020.


Re your update showing this code:

var ObjectUtils ??= ChromeUtils.import("resource://gre/modules/ObjectUtils.jsm").ObjectUtils;

...it's not an ESLint or ??=-specific thing, that's just not a valid place to use a compound assignment operator (any of them). Here's an example using += in JavaScript (no linter):

var a += 42;
//    ^−−−−−−−− SyntaxError: Unexpected token '+='
console.log(a);

In the normal case, you'd just want an assignment operator (ideally using let or const; var shouldn't be used in new code):

let ObjectUtils = ChromeUtils.import("resource://gre/modules/ObjectUtils.jsm").ObjectUtils;

In a very unusual situation where you had to declare a variable that might already be declared and use its current value if it's not nullish, you'd have to separate that into two parts:

// **VERY** rare use case, there are better options
var ObjectUtils; // Possibly a redeclaration
ObjectUtils ??= ChromeUtils.import("resource://gre/modules/ObjectUtils.jsm").ObjectUtils;

But I wouldn't do that in new code. :-)