https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Hi all, Thanks for the wonderful guides. I thought of an improvement with the following code example on the Closures page
as written on the page:
If you don't want to use more closures, you can use the let keyword introduced in ES2015 :
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (**var i = 0**; i < helpText.length; i++) {
**let item** = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
I would suggest using let in the first expression given to the for loop (let i = 0). I think adding let to the 'item' variable misses a teaching opportunity for a common pattern, used elsewhere on other MDN pages, such as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
Thanks,
Brant
Happy to take this one 馃憢 @chrisdavidmills
Awesome - assigned to you @jadjoubran (saving Chris a little time!)
@jadjoubran Do you still plan to work on this, or should we un-assign it?
Hey @sideshowbarker, yes I'll work on it this weekend
Hey @brantphoto
Thanks for opening the issue.
Just to double check, the code you're referring to is eventually re-written with let at the end of that paragraph. See:
If you don't want to use more closures, you can use the let keyword introduced in ES2015 :
function showHelp(help) {
document.getElementById('help').textContent = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (let i = 0; i < helpText.length; i++) {
let item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
But, this is the solution to the problem explained above. Do you perhaps just want to improve the first block of code to have let i = 0; instead of var i = 0;? I believe the reason why it exists is to show how old/legacy code used to be (so then it would make sense to use var as let did not exist yet)
Please let me know if I'm missing anything, thanks!
@jadjoubran looking back at this issue either I didn't see the second example with let or the page has changed since I first posted this issue. I don't think there is currently an issue