Do you know the closures well?

Challenge Go to this task on javascript.info site -> Army of function (Stop reading from here, go perform the task first! Adding an image below so that you don't accidently read my solution) My experience after solving this I implemented a bit different approach, since the question is inside a chapter where every problem was solved by defining a higher order function. So my solution looked something like this: [This is NOT the full and final solution] function makeArmy() { let shooters = []; // I created a generateShooter function function generateShooter(number) { return function () { console.log(number); }; } while (i < 10) { let shooter = generateShooter(i); shooters.push(shooter); // and add it to the array i++; } // ...and return the array of shooters return shooters; } let army = makeArmy(); // all shooters show 10 instead of their numbers 0, 1, 2, 3... army[0](); // 0 army[1](); // 1 army[2](); // 2 The catch (If you have read the solution completely on the javascript.info site, then you might not be reading this, but since you are here, let me serve the essence of this problem to you!) Simply switch from the while loop to for loop!

Mar 30, 2025 - 17:10
 0
Do you know the closures well?

Challenge

Go to this task on javascript.info site -> Army of function
(Stop reading from here, go perform the task first! Adding an image below so that you don't accidently read my solution)

Mai nahi bataunga

My experience after solving this

I implemented a bit different approach, since the question is inside a chapter where every problem was solved by defining a higher order function.

So my solution looked something like this: [This is NOT the full and final solution]

function makeArmy() {
  let shooters = [];

  // I created  a generateShooter function
  function generateShooter(number) {
    return function () {
      console.log(number);
    };
  }

  while (i < 10) {
    let shooter = generateShooter(i);
    shooters.push(shooter); // and add it to the array
    i++;
  }

  // ...and return the array of shooters
  return shooters;
}

let army = makeArmy();

// all shooters show 10 instead of their numbers 0, 1, 2, 3...
army[0](); // 0
army[1](); // 1
army[2](); // 2

The catch

(If you have read the solution completely on the javascript.info site, then you might not be reading this, but since you are here, let me serve the essence of this problem to you!)

Simply switch from the while loop to for loop!