Jump to content

Loop not working with function


mcse

Recommended Posts

var greeting = (function() {  var i = 0;  return function(name) {    alert('My name is ' + name + " " + i++);  };})();for (var k=0; k<=5; k++) { // i could be used here greeting('Jeremy');  // My name is Jeremy k}
Link to comment
Share on other sites

The issue you are experiencing here is what Dave J solved by using a closure. In your example, the reason you always get 6 is because that is the last value of i, since Javascript passes value by reference. So for every call to greetings, it will always output the last value assigned to i. To get around this, a closure can provide an isolated scope if you will, capturing the value of i for that unique iteration, so that value is preserved, and not always displaying the last value assigned to i. MDN has a good article on this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...