Skip to content

Commit

Permalink
Fixing code issues.
Browse files Browse the repository at this point in the history
As you can see by executing the code, it does not produce the results described in the article. I've added some fixes in order for the code to produce the appropriate results.
  • Loading branch information
kostasx authored May 23, 2019
1 parent 71ab41f commit 84ac44b
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 84ac44b

Please sign in to comment.