0

Why JavaScript forbids it (gives syntax error), if Nullish operator (??) is combined with And (&&), OR (||) operators "without parenthesis"?

Example:

let x = 1 && 2 ?? 3; // Syntax error

But following works

let x = (1 && 2) ?? 3; // Works
alert(x);
Sourabh Saxena
  • 127
  • 1
  • 1
  • 7
  • 2
    Perhaps to force script-writers to write code that makes more intuitive sense - the precedence of ?? compared to && isn't obvious without looking it up first – CertainPerformance Oct 15 '21 at 04:45
  • 1
    [No chaining with AND or OR operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator#no_chaining_with_and_or_or_operators): _"providing parenthesis to explicitly **indicate precedence** is correct"_ (emphasis mine). This quote gives a hint as to why it is not allowed. – Yousaf Oct 15 '21 at 04:49
  • 2
    https://github.com/tc39/proposal-nullish-coalescing/issues/48 – Robby Cornelissen Oct 15 '21 at 04:52
  • 2
    https://github.com/tc39/proposal-nullish-coalescing/issues/58 – Robby Cornelissen Oct 15 '21 at 04:53

0 Answers0