+ 1
Why is this code alerting "1111" instead of "1112"?
This is the code of a challenge: var a = 10; var b = 11; var c; if(!(a++ >= 10 || b++ >= 11)){ c = a+b; alert(a + "" + c); }else{ alert(a + "" + b); }
6 odpowiedzi
+ 3
a++ and b++ returns current values of a and b and increments each.
in the if statement a is 10 so a++>=10 is true so since || in an if statement returns true if any condition is true the next condition wont execute so b remains 11.
now because of the ! (NOT) in the if statement the final state is false so the else block is execute for which a has been incremented to 11 while b hasn't changed.
so inside the else, a= 11 and b = 11
+ 2
This is what happen :
a=10
a++ >= 10 // true --> 10 >= 10
we have a '||' so the statement is true
However, there is '!' so the condition is false
We go to the 'else'
a was equal to 10 but in the 'if' statement, there was 'a++' so a=11 and b=11
In a 'if' statement with a '||' operator, if the first condition is true, the second isn't evaluated.
Ask if you don't understand
+ 1
!a++>=10 is false, so it go to the else statement and b never increments
+ 1
Thanks a lot to you all!
I thought logical expressions are always evaluated completely.
0
!(a++ >= 10) || !(b++ >= 11) will do that you want
0
( !(a++ >= 10 || b++ >= 11) )
1. a++ >= 10 is true so b is not evaluated
2. all becomes false and it's incremented
3. go to else statement
( !(a++ >= 10) || !(b++ >= 11) )
1. a++ >= 10 is true
2. it becomes false and it's incremented. b has to be evaluated
3. b++ >= 11 is true
4. it becomes false and it's incremented
5. go to else statement