Skip to content

Commit f97e095

Browse files
Add for...of loop with const as modern best practice to "Creating closures in loops: A common mistake" (mdn#40654)
* Add for...of with `const` as best practice to "Creating closures in loops" * Punctuation, wording * Update index.md --------- Co-authored-by: Joshua Chen <sidachen2003@gmail.com>
1 parent 7c98b54 commit f97e095

File tree

1 file changed

+10
-18
lines changed
  • files/en-us/web/javascript/guide/closures

1 file changed

+10
-18
lines changed

files/en-us/web/javascript/guide/closures/index.md

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -492,28 +492,20 @@ setupHelp();
492492

493493
This example uses `const` instead of `var`, so every closure binds the block-scoped variable, meaning that no additional closures are required.
494494

495-
Another alternative could be to use `forEach()` to iterate over the `helpText` array and attach a listener to each [`<input>`](/en-US/docs/Web/HTML/Reference/Elements/input), as shown:
495+
If you are writing modern JavaScript anyway, you can consider more alternatives to the plain `for` loop, such as using {{jsxref("Statements/for...of", "for...of")}} loop and declaring `item` as `let` or `const`, or using the {{jsxref("Array/forEach", "forEach()")}} method, which both avoid the closure problem.
496496

497497
```js
498-
function showHelp(help) {
499-
document.getElementById("help").textContent = help;
500-
}
501-
502-
function setupHelp() {
503-
var helpText = [
504-
{ id: "email", help: "Your email address" },
505-
{ id: "name", help: "Your full name" },
506-
{ id: "age", help: "Your age (you must be over 16)" },
507-
];
508-
509-
helpText.forEach(function (text) {
510-
document.getElementById(text.id).onfocus = function () {
511-
showHelp(text.help);
512-
};
513-
});
498+
for (const item of helpText) {
499+
document.getElementById(item.id).onfocus = () => {
500+
document.getElementById("help").textContent = item.help;
501+
};
514502
}
515503

516-
setupHelp();
504+
helpText.forEach((item) => {
505+
document.getElementById(item.id).onfocus = () => {
506+
showHelp(item.help);
507+
};
508+
});
517509
```
518510

519511
## Performance considerations

0 commit comments

Comments
 (0)