Middle+
How to make the makeBook function return expected values 0 and 5 instead of two dozens?
sobes.tech AI
Answer from AI
The problem with the makeBook function returning twice 10 instead of 0 and 5 is most likely related to variables used to form the result being captured in a closure or modified within a loop.
Here's an example in JavaScript where this error often occurs:
function makeBook() {
let result = [];
for (var i = 0; i < 2; i++) {
result.push(function() { return i * 5; });
}
return result.map(f => f());
}
console.log(makeBook()); // [10, 10]
Here, var i is the same variable, and by the time the functions are called, i equals 2, so 2*5=10.
To fix this, you should use let to create a new variable in each iteration:
function makeBook() {
let result = [];
for (let i = 0; i < 2; i++) {
result.push(function() { return i * 5; });
}
return result.map(f => f());
}
console.log(makeBook()); // [0, 5]
Alternatively, you can use a closure:
function makeBook() {
let result = [];
for (var i = 0; i < 2; i++) {
(function(j) {
result.push(function() { return j * 5; });
})(i);
}
return result.map(f => f());
}
console.log(makeBook()); // [0, 5]
Thus, to make the function return the expected values 0 and 5, you need to correctly close over the loop variable.