Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing code issues. #432

Merged
merged 1 commit into from
May 23, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.