[beta] Improve challengeSeed for "ES6: Scopes and the var keyword"
See original GitHub issueES6: Scopes and the var keyword
Issue Description
The editor shows an error for line 6 of the initial challengeSeed
, stating that we shouldn’t create functions within loops. We can avoid this by moving this function definition out of the loop and only reference it in the loop.
Updated challengeSeed
:
var newCampers = [{camper: "Wil"}, {camper: "Sam"}, {camper: "Dav"}];
function roleCall (i) {
return "Camper # " + (i + 1) + " has arrived.";
}
// only change code below this line
for (var i = 0; i < newCampers.length; i++) {
// only change code above this line
newCampers[i].roleCall = roleCall.bind(null, i);
}
console.log(newCampers[0].roleCall());
console.log(newCampers[1].roleCall());
console.log(newCampers[2].roleCall());
However, this also means we lose the closure that gives us access to i
. Since code isn’t supposed to be written like this anyway, I think we’re better of by using roleCall.bind(null, i)
, despite the increased complexity. The code above works just like the previous example, but uses better (if not best) practices.
Even better, @BrendanSweeny suggested this could further be improved:
var newCampers = [{camper: "Wil"}, {camper: "Sam"}, {camper: "Dav"}];
function roleCall (i) {
return "Camper # " + (i + 1) + " has arrived.";
}
// only change code below this line
for (var i = 0; i < newCampers.length; i++) {
// only change code above this line
newCampers[i].roleCall = roleCall.bind(null, i);
}
console.log(newCampers[0].roleCall());
console.log(newCampers[1].roleCall());
console.log(newCampers[2].roleCall());
console.log(typeof i);
By adding a console.log()
, the camper can see that using let
will cause typeof i
on the last line to be "undefined"
.
@BrendanSweeny also had an idea about adding an extra test to verify that i ===
. I think this is a good idea.
Building upon Brendan’s test case from https://github.com/freeCodeCamp/freeCodeCamp/pull/12956#discussion_r98820528, this could be what we’re looking for.
assert.isUndefined(i, 'message: <code>i</code> should not be available outside of the <code>for</code> loop.');
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (5 by maintainers)
Top GitHub Comments
Absolutely! I’ll create a PR sometime this weekend.
@HKuz It’s not introduced anywhere (AFAIK) 😢 It’s a really nice language feature.
If we want to use the simpler example, we’d need to update both the seed as well as the instructions. @BrendanSweeny Would you like to create the PR for this, as you came up with the solution? ☺️