1

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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So the for-loop does actually increment the variable to 3, but it cease the following operation since the conditional fails (because 3 < 3 is false)? Oh wow thank you so much, I completely thought the for-loop stops counting up when the variable hits 2..!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.