0

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?

6
  • 1
    The inner_i is 2 in your third loop which means: counter+=inner_i equals 11+2=13 just return counter + inner_i Commented Jun 10, 2016 at 10:53
  • return counter + inner_i; Commented Jun 10, 2016 at 10:53
  • "What am I doing differently?" How are we to know? You haven't shown the code you're comparing your code to. Commented Jun 10, 2016 at 10:57
  • Thanks guys! Not seeing the forest for the trees! Commented Jun 10, 2016 at 10:57
  • @T.J.Crowder: It's in the link I provided. Commented Jun 10, 2016 at 11:00

1 Answer 1

3

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot!! Totally didn't see that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.