FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
The following code creates an array of functions. Every function is meant to output its number. But something is wrong:
function createFunctions() {
let functions = [];
let i = 0;
while (i < 10) {
let func = function() {
console.log(i);
};
functions.push(func);
i++;
}
return functions;
}
const funcs = createFunctions();
// all functions show 10 instead of their numbers 0, 1, 2, 3...
funcs[0](); // 10 from the function at index 0
funcs[1](); // 10 from the function at index 1
funcs[2](); // 10 ...and so on.
Why do all of the functions show the same value?
Fix the code so that they work as intended.
Template
index.js
export function createFunctions() {
const functions = [];
let i = 0;
while(i < 10) {
let func = function () {
console.log(i);
};
functions.push(func);
i++;
}
return functions;
}
index.test.js
import { createFunctions } from "./index";
describe("createFunctions function", () => {
let funcs;
beforeEach(() => {
funcs = createFunctions();
});
test('should create an array of functions', () => {
expect(funcs.length).toBe(10);
funcs.forEach((func, index) => {
expect(typeof func).toBe('function');
});
});
test("each function should log its own number", () => {
const consoleLogSpy = jest
.spyOn(console, "log")
.mockImplementation(() => {});
funcs.forEach((func, index) => {
func();
expect(consoleLogSpy).toHaveBeenLastCalledWith(index);
});
consoleLogSpy.mockRestore();
});
});
Info
Question
The following code creates an array of functions. Every function is meant to output its number. But something is wrong:
Why do all of the functions show the same value?
Fix the code so that they work as intended.
Template
index.js
index.test.js
package.json