NotSmartButLucky
NotSmartButLucky

Reputation: 73

closures in for loops in javascript

I am trying to reproduce the example with the IIEF here:

Understand JavaScript Closures With Ease

EDIT

It's under 3. Closures Gone Awry

This is my code:

var myArray = ["a", "b", "c"];

function doSomething(someArray) {
  var counter = 10;
  for (var i = 0; i < someArray.length; i++) {
    someArray[i] = function(inner_i) {
      return function() {
        return counter += inner_i;
      }();
    }(i);
  }
  return someArray;
}

var newArray = doSomething(myArray);
console.log(newArray[0]);
console.log(newArray[1]);
console.log(newArray[2]);

The output is

10
11
13

instead of

10
11
12

What am I doing differently?

Upvotes: 0

Views: 62

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115202

There is nothing wrong in the result, because you are updating the value of counter in each iteration. Instead just return the sum of counter and i.

var myArray = ["a", "b", "c"];

function doSomething(someArray) {
  var counter = 10;
  for (var i = 0; i < someArray.length; i++) {

    someArray[i] = function(inner_i) {
      return function() {
        return counter + inner_i;
      }();
    }(i);
  }

  return someArray;
}

var newArray = doSomething(myArray);
console.log(newArray[0]);
console.log(newArray[1]);
console.log(newArray[2]);

Upvotes: 3

Related Questions