0

In a JavaScript tutorial I saw someone using the ?? operator over a short circuit operator i.e. ||

For Example:

const a = null;
const b = a ?? 0

Which essentially meant use the value of a and if a is null or undefined use a default value of 0.

But somehow in NodeJS, this results in a syntax error:

Screenshot

Daniel_Knights
  • 5,599
  • 3
  • 10
  • 32
deAr
  • 1
  • 2
  • 3
    You're using Node 12, it's available in Node 14 – VLAZ Mar 21 '21 at 11:28
  • Lemme give it a try. – deAr Mar 21 '21 at 11:30
  • Also, What is this operator called? – deAr Mar 21 '21 at 11:30
  • It's called Nullish Coalescing – Ismail Dinar Mar 21 '21 at 11:31
  • [Nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) - I checked the table at the bottom for the Node version – VLAZ Mar 21 '21 at 11:31
  • Thanks you so much. Google is killing me when I search '??'. Apparently Google's just ignoring question marks in searches. Appreciate it. – deAr Mar 21 '21 at 11:33
  • See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) and [statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements). Simply Google “JavaScript double question mark operator” or something. – Sebastian Simon Mar 21 '21 at 11:34
  • 1
    @deAr yeah, searching for operators is *not easy* with google. Same happens if you search for dots and similar. For these kinds of searches, you can use [SymbolHound](http://symbolhound.com/). You can also restrict which sites it searches in. For JS, we have a canonical list that is easier to search here: [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780). You can find the link in the tag description for [[tag:javascript]] - it's almost at the bottom. – VLAZ Mar 21 '21 at 11:36
  • I'm loving these operators. Thank you for letting me know these specific details guys. <3 – deAr Mar 21 '21 at 11:40

1 Answers1

0

?? Called Nullish coalescing operator in Javascript.

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

console.log(null ?? null)
// expected output: null

|| this operator not return 0, false, null, "" and undefined. Ex. a = 0; b = 10; console.log(a || b); it return 10(b).

If first value is NULL then it return second value.

Note: if second value also NULL then it return null

Sagar
  • 21
  • 2