B
B
Barrakuda742018-02-19 12:25:18
JavaScript
Barrakuda74, 2018-02-19 12:25:18

Why is x not equal to one in if (6 || 5 && (x = 1))?

var x = 0
if (6 || 5 && (x = 1)) document.write(x); // 0

As far as I know, the '&&' operator has higher precedence than the '||' operator.
However, the right operand is not executed, why?
PS: Issue resolved. To understand the answer, please read the comments to the solution. Parentheses have nothing to do with it (and operator precedence too).

Answer the question

In order to leave comments, you need to log in

7 answer(s)
A
Anton fon Faust, 2018-02-19
@Barrakuda74

because, in fact, your expression looks like this:

var x = 0
if (6 || (5 && (x = 1))) document.write(x); // 0

logical operator || works like this: if the first operand can be cast to true, the rest of the expression is not evaluated.
https://tc39.github.io/ecma262/#sec-binary-logical...
the second part of clause 12.13.3 concerns just the case indicated at the beginning of the discussion.

I
imhuman, 2018-02-19
@imhuman

6 evaluates to true, the rest of the expression is simply ignored as having no effect on the result

S
Sergey Epifanov, 2018-02-19
@kacheleff

js interpreter first arranges brackets according to operator precedence, and then evaluates expressions. it turned out that the brackets were placed like this , and then the interpreter realized that the right part || do not need to perform (6 || (5 && (x = 1)))

E
eRKa, 2018-02-19
@kttotto

Maybe because you do not compare x with 1, but assign a unit to x?

G
GreatRash, 2018-02-19
@GreatRash

These synthetic questions from interviews infuriate ...
Because, for starters, the person who writes such code needs to be beaten on the hands with a ruler.

J
Jaroslaw Goszowski, 2018-02-19
@goszowski

It's the same as writing if(6) {}
If the first part of the condition returns anything, then the other part is ignored.
To check also the second part of the condition, you need to either compare 6 with something, or instead of || (or) write && (and)

N
nelolka, 2018-02-19
@nelolka

but he just didn’t go further than 6, because he brought it to true

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question