+ 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......
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.
+ 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