Rnwego
June 10, 2021, 4:42pm
1
Tell us what’s happening:
Describe your issue in detail here.
var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
How does console display the value 2? I’m confused
Rnwego
June 10, 2021, 4:44pm
2
I meant how does it console display the value 3*
@Rnwego The printNumTwo
variable is declared as function that return value of i
when i
is equals to two. But the the loop is still going after the function is declared. Which mean, i
become 3
so that the function return 3
instead of 2
.
1 Like
Rnwego
June 10, 2021, 5:32pm
4
I’m sorry I’m still a little confused. Why is the loop still going when the condition is for i < 3
In the beginning i=0. Is it less than 3? i<3? Yes then we enter the loop.
Inside the loop is i=2? No! So we skip what’s inside the bracket.
Next thing is i is incremented by 1 because of i++. Now i is 2. So we check is i<3. Yes! We enter inside the for loop’s brackets again.
Then we do the check again is i==2? Yes because i is indeed 2 now. Thus we return i which is what gets printed.
1 Like
system
Closed
December 10, 2021, 6:46am
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.