jsartisan / frontend-challenges

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.
https://frontend-challenges.com
20 stars 3 forks source link

Closure 2 #99

Closed jsartisan closed 1 week ago

jsartisan commented 1 week ago

Info

difficulty: easy
title: Closure 2
type: question
template: javascript
tags: javascript, closure

Question

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();
  });
});

package.json

{
  "dependencies": {},
  "main": "/index.js",
  "devDependencies": {}
}
github-actions[bot] commented 1 week ago

100 - Pull Request updated.