Pergunta

All this time my thinking of short circuit evaluations seems to be wrong.

In javascript:

var a = false, b = true, c=true;
a && b || c; // Evaluates to true

Compared to

var a = false, b = true, c=true;
a && (b || c); // Evaluates to true

Why doesn't the VM stop when it sees that a is false?

More explicit example:

function a(){
  console.log("I'm A");
  return false;
}
function b(){
  console.log("I'm B");
  return true;
}
function c(){
  console.log("I'm C");
  return true;
}

a() && b() || c();

The output is:

I'm A
I'm C
true

So apparently

a && b || c === (a && b) || c

So I'm confused, why does it automatically wrap the a && b together? What exactly is the order of operations for these expressions?

Do most languages adhere to this order (PHP seems to be like this)?

Foi útil?

Solução

These simple rules apply:
- shortcuts in logical expression evaluation does not mean that expressions are evaluated incorrectly, i.e. the result is the same with or witout shortcutting;
- the AND boolean operator (&&) is of higher precedence than the OR (||). This is why a && b are 'wrapped' together;
- it is not safe to rely on precedence order, use parentheses ; this improves readability too;
- most languages do shortcuts when evaluating logical expressions if the result is already defined, incl. PHP; There are exceptions however most notably in reverse polish notation languages like PostScript.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top