Skip to content

Instantly share code, notes, and snippets.

@tobi
Created April 9, 2011 21:32
Show Gist options
  • Select an option

  • Save tobi/911797 to your computer and use it in GitHub Desktop.

Select an option

Save tobi/911797 to your computer and use it in GitHub Desktop.
wtf.js
var ary = ['a', 'b', 'c'];
var funcs = [];
for (var i = 0; i < ary.length; i++) {
var c = ary[i]
funcs.push(function() { console.log(c) })
};
for (var i = 0; i < funcs.length; i++) {
funcs[i]();
};
@narensisodiya

Copy link
Copy Markdown

I think, the same c is visible to all function, which have the latest assigned value.
as variable scope in javaScripts is only function level so you can initialize var c in function that will work,

  funcs.push(function() { var c = ary[i]; console.log(c) }) 

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