/    Sign up×
Community /Pin to ProfileBookmark

Wrapping For loop in an IIFE

New to learning IIFE. The following code returns 0, 1, 2:

[CODE]

<!DOCTYPE html>
<html>

<head>

<script>

var a = [];
for (var i=0;i<3; i++) {

(function(j) {
a[j] = function() {
console.log(j);
};
})(i);
}
a[0]();
a[1]();
a[2]();
</script>
</head>
<body>
<h1></h1>
</body>

</html>

[/CODE]

Trying to wrap the for loop code in an IIFE to get the same result. No success. Here’s what I’ve tried:

[CODE]

<!DOCTYPE html>
<html>

<head>

<script>

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

</script>
</head>
<body>

</body>

</html>

[/CODE]

to post a comment
JavaScript

0Be the first to comment 😎

×

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.7,
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,
)...