Skip to content

Commit

Permalink
Merge pull request loverajoel#432 from kostasx/master
Browse files Browse the repository at this point in the history
Fixing code issues.
  • Loading branch information
zenopopovici authored May 23, 2019
2 parents 71ab41f + 84ac44b commit d123542
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions _posts/en/javascript/2017-06-14-closures-inside-loops.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ If you ever come across the likes of
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("i value is" + i);
console.log("i value is " + i);
};
}

for (var i = 0; i < 3; i++) {
funcs[i]();
for (var k = 0; k < 3; k++) {
funcs[k]();
}
```

Expand All @@ -38,9 +38,9 @@ i value is 2
Doesn't match the actual output which will resemble

```
i value is 2
i value is 2
i value is 2
i value is 3
i value is 3
i value is 3
```

This is because of how the capturing mechanism of closures work and how `i` is represented internally.
Expand All @@ -50,7 +50,7 @@ To solve this situation you can do as follows:
```javascript
for (var i = 0; i < 3; i++) {
funcs[i] = (function(value) {
console.log("i value is " + 3);
console.log("i value is " + i);
})(i);
}
```
Expand All @@ -60,9 +60,9 @@ Which effectively copies i by value by handing it to our closure or
```javascript
for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("i value is " + 3);
console.log("i value is " + i);
}
}
```

Where `let` scopes the variable to our `for` loop and produces a new value each iteration, thus `i` will be bound to different values on our closures as expected.
Where `let` scopes the variable to our `for` loop and produces a new value each iteration, thus `i` will be bound to different values on our closures as expected.

0 comments on commit d123542

Please sign in to comment.