Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
because, in fact, your expression looks like this:
var x = 0
if (6 || (5 && (x = 1))) document.write(x); // 0
6 evaluates to true, the rest of the expression is simply ignored as having no effect on the result
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)))
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.
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question