Menu
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>
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>