+ 4

Very basic JS question

let x = 0; if(x){ x = 100; } console.log(x); let y = 1; if(y>=1) { y = 2; } console.log(y); Can someone kindly tell me why x console logs 0 yet y console logs 2 and not 1?

10th Feb 2020, 9:18 AM
Christine
4 odpowiedzi
+ 9
y = 2 because the condition in if statement is true ( 1 >= 1 ) x does not equal 100 because the condition in if statement is false. When x is 0, type coercion to boolean is false.
10th Feb 2020, 9:27 AM
Gordon
Gordon - avatar
+ 3
x is 0, It is special case in JavaScript, that 0 is evaluated as false.
10th Feb 2020, 11:10 AM
Gordon
Gordon - avatar
+ 2
oh... bear with me as i am a newbie. so an if condition expression always has to be either true or false (or truthy or falsy). so in the first example, if(x) is evaluated as false or falsy so the block of code will not run. i was confused since i thought the value of x inside the () just got updated to 100 since x met the if condition by virtue of having its value declared.
10th Feb 2020, 9:37 AM
Christine