简体   繁体   中英

How do JavaScript for-loop work with a variable

I am new to JavaScript and there's something I am struggling to understand…

for(var i = 0; i < 3; i++) {
    console.log(i)
}
console.log(i);

Here's a piece of codes and when I see this, right off the bat I thought the out put is going to be something like,

//0
//1
//2
//2

Since the for loop counts up to 2 and leaves the variable as 2, I thought the output will be 2 if I log it out after the for loop. But the output was different from what I expected.. (instead of 2, it spits out 3 when it's logged after the for loop)

//0
//1
//2
//3

I read the several articles and they do explain that the variable's scope is global and that, but I still don't get why I get 3 as an output.

(One of the articles I read: https://www.freecodecamp.org/news/thrown-for-a-loop-understanding-for-loops-and-timeouts-in-javascript-558d8255d8a4/ )

I'd really appreciate your help, thanks in advance.

Think about it for a moment, if i is 2 then the loop would still run because 2 < 3 . At the end of this loop when i = 2 it will use i++ , hence i is now 3 . And now the conditional fail because 3 < 3 is false, so it exits. Hence i remains 3 .

3 is the first number on i that would abort the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM