Skip to content

Instantly share code, notes, and snippets.

@chrisbodhi
Created August 1, 2015 16:08
Show Gist options
  • Select an option

  • Save chrisbodhi/f65aeee339eb30f2720b to your computer and use it in GitHub Desktop.

Select an option

Save chrisbodhi/f65aeee339eb30f2720b to your computer and use it in GitHub Desktop.
What will the value of `i` be in the alert box when `first()` and `tenth()` are called?
function makeGalaxy(size) {
var stars = [];
for (var i = 0; i < size; i++) {
stars.push(function(){alert("This is star #" + i);});
}
return stars;
};
var galaxy = makeGalaxy(20);
var first = galaxy[0];
first();
var tenth = galaxy[9];
tenth();
@chrisbodhi
Copy link
Author

Changes to makeGalaxy to have it behave as expected:

function makeGalaxy(size) {
  var stars = new Array(size).fill(0);
  return stars.map((star, index) => {
    return () => {alert(`This is star #${index}`)};
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment