So I’m trying to really understand how var works in JavaScript I understand that if you use keyword var that variable become accessible to the rest of the function or the program so what i did to experiment was I said
for(var x=1; x<=3;x+=1){ //No code here } console.log(x)
It returned 4
I’m not really sure why It came back with number4 when I said x<=3 which means if x is less than or equil to 3 run 3 times but it seems to have run 4.I also understand that calling console.log(x) will get the final value, which should be 3 not 4 BTW me using var and calling for x outside the loop is intentional just not sure why it’s not displaying 3
Because the condition isn't false until x is 4, consider the following values for x and match that against the condition:
Is 1 less than or equal to 3? Yes
Is 2 less than or equal to 3? Yes
Is 3 less than or equal to 3? Yes
Is 4 less than or equal to 3? No
For x to be 3 at the end, the condition needs to change to be x less than 3. Since 3 is not less than 3, it is equal.
The statement inside the loop runs 3 times, but the incrementor and the condition will run 4 times. The loop exits when the condition is false, so it has to increment once more after x has been set to 3. Only when x is 4 or greater will the condition be false, and the loop stops.