/    Sign up×
Community /Pin to ProfileBookmark

The return from a For loop

I’m not understanding why the code below returns the number 3, three times.

The piece of code

[CODE]for(var i=0; i<3; i++)[/CODE]

starts the value of i at 0. Then, it says as long as i is less than 3, the value increases by one. So, it seems to me the values of 1 and 2 would get passed to console.log(i) and then stop because it says i<3. What am I not undestanding?

Here’s the full program:

[CODE]
<!DOCTYPE html>
<html>
<body>

<p>

</p>

<script>
var a = [];
for(var i=0; i<3; i++) {
a[i] = function() { console.log(i) };
}

a[0]();
a[1]();
a[2]();
</script>

</body>
</html>

[/CODE]

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumNov 04.2017 — This is a common problem. For explanation and solutions read this:

http://www.webdeveloper.com/forum/showthread.php?363139-For-loop-not-working-help

Shortened:

After the loop is finished, the value of i is 3. Thus 3 is logged three times.

Solution:
for (var i = 0; i &lt; 3; i++) {
a[i] = function (idx) { return function() { console.log(idx) } }(i);
}

Alternative solution: use "let" instead of "var":
for (let i = 0; i &lt; 3; i++) {
a[i] = function () { console.log(i) };
}
This is more easy and short but I'm not shure about browser support.
×

Success!

Help @MichiKen spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...