I was looking into how to set a variable in javascript and I found out about the Nullish coalescing operator (??) in one of the posts I saw on here.
But now, when I try to use it, I get this error:
Unexpected token, expected ,
for this line:
var oldBookScript = (localStorage.getItem(book.id) ?? newBookScript);
I want the variable oldBookScript
to have the value of localStorage.getItem(book.id)
but if that is null or empty, I want it to have the value of newBookScript
Do I need to enable it somehow?
Thanks!
I was looking into how to set a variable in javascript and I found out about the Nullish coalescing operator (??) in one of the posts I saw on here.
But now, when I try to use it, I get this error:
Unexpected token, expected ,
for this line:
var oldBookScript = (localStorage.getItem(book.id) ?? newBookScript);
I want the variable oldBookScript
to have the value of localStorage.getItem(book.id)
but if that is null or empty, I want it to have the value of newBookScript
Do I need to enable it somehow?
Thanks!
It is a syntactical construct, which means that in order to run code with it, you need to be in an environment that's up-to-date enough to support it.
For example, the most recent versions of Node, Chrome, and Firefox (among others) will all run fine with your code, but older environments (like IE11) will throw a SyntaxError.
In standard scripts, given that it's syntax, there's no way to "enable" it on a particular environment - either it's supported or it isn't. The usual approach in this situation is to use Babel to transpile the source code (which has all the modern syntax) down to ES6 or ES5 so that obsolete browsers can understand it.
But if you're using React, your code's JSX is already being transpiled. The most up-to-date versions of create-react-app does support the nullish coalescing operator. Upgrade to a more recent version of create-react-app, if possible. If you have a more manual setup, you'll need to make sure your code is being transpiled with Babel and use Babel 7.8.0 or later.
See these docs from Babel on integrating it into React via the @babel/preset-react
preset.