Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me with the below code, it is giving a wrong output.

var funcs = [];

// let's create 3 functions

for (var i = 0; i < 3; i++) {

  // and store them in funcs

  funcs[i] = function() {

    // each should log its value.

    console.log("My value: " + i);

  };

}

for (var j = 0; j < 3; j++) {

  // and now let's run each one to see

  funcs[j]();

}

Output :

My value: 3

My value: 3

My value: 3

Output what I want:

My value: 0

My value: 1

My value: 2

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

The problem is within the variable i, which is been bound to the same variable which is outside the function. So, we need to bind the variable to each function with a separate and unchanging value like this:

var funcs = [];

function createfunc(i) {

  return function() {

    console.log("My value: " + i);

  };

}

for (var i = 0; i < 3; i++) {

  funcs[i] = createfunc(i);

}

for (var j = 0; j < 3; j++) {

  // and now let's run each one to see

  funcs[j]();

}

I hope this will help.

Want to know more about Java? Prefer this tutorial on Java Tutorial.

Want to become a Java Expert? Join Java Course now!!

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...