I am actually a newbie to javascript and just to learn the basics, I’ve started taking lessons on codecademy.
var i;
for (i = 1; i <= 40; i++) {
console.log("i is now equal to " + i);
}
Here’s my question – In this code, when i <= 40, it should print till 41, no? Because the for loop continues to run until the condition i <= 40 is true but why is that it only prints till 40 then?
i.e.
When it runs at 40, it would print till 41 by incrementing it once, no? Then why is it that it prints only till 40?
If someone also explained me what exactly the code does and what each line means and does, I’d be really very grateful. Thanks.
it says the following
this means it will print out the number 1 the first time and each time increment by 1 until such time i is equal to 41 at which time the loop will finish (but will do no more operations between the
{‘s meaning 41 will never be printed)if you had written the following
it would make no different aside the count would start from 0, one more iteration but it would still exit when i became equal to 41 but it still wouldn’t print 41
If you were to do another log statement outside the loop you’d find that i is equal to 41 but this value was never used in the body of the loop (the bit in curly braces)