+ 2

mindboggling JS code - if(x)...

It's simple, but I don't quite get it: var x = 1; if(x){ x=0; } if(x){ x=1; } alert(x); If I understand it right, the first "if" changes the x value to 0, and the second "if" thinks x is no longer x. but why? X is changed, but it is still x......

8th Apr 2017, 9:40 PM
Simon Nadolski
Simon Nadolski - avatar
2 Answers
+ 5
x = 1 if (1) { x = 0 } 1 means true -> x = 0 if (0) { x = 1 } 0 means false -> Nothing happens. alert(x) x = 0 is alerted.
9th Apr 2017, 1:31 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 3
JS evaluates 1 to true and 0 to false. Therefore only the instruction of the first if block will execute, changing the value of x from 1 to 0. if 1==true x becomes 0 if (0==true) //doesn't execute, therefore x remains 0
8th Apr 2017, 9:50 PM
seamiki
seamiki - avatar