skip to Main Content

Why this code is error:

console.log(true&&false??true)

But this code is no error:

console.loge((true&&false)??true)

Or this example why B() does not run:

function A() { console.log('called A'); return false; }
function B() { console.log('called B'); return false; }
function C() { console.log('called C'); return true; }

console.log(C() || B() && A());

// Logs:
// called C
// true

2

Answers


  1. The answer to "why does this work this way" here is because it’s defined to work that way.

    You can find the rules for short-circuiting logic and the precedence of operators and basically everything else about JavaScript in the MDN web documentation (other references are available):

    Login or Signup to reply.
  2. For the first part of the question, see here.

    [T]he precedence between ?? and &&/|| is intentionally undefined, because the short circuiting behavior of logical operators can make the expression’s evaluation counter-intuitive. Therefore, the following combinations are all syntax errors, because the language doesn’t know how to parenthesize the operands:

    a ?? b || c;

    a || b ?? c;

    a ?? b && c;

    a && b ?? c;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search