Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Created April 11, 2014 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasBurleson/10438374 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/10438374 to your computer and use it in GitHub Desktop.
JavaScript - Qualification Test (Senior) > Closures
function init(list)
{
var result = [ ];
for (var i=0; i<list.length; i++)
{
var item = 'item' + list[i];
result.push( function() {
console.log( item + ' ' + list[i]);
});
}
return result;
}
function foo()
{
var list = init([1,2,3]);
for ( var j=0; j<list.length; j++)
{
list[j]();
}
}
foo();
@ThomasBurleson
Copy link
Author

Question: What does foo() print to the console?

Question: How would you fix it to log
item1 1
item2 2
item3 3

@ThomasBurleson
Copy link
Author

// Code goes here

function init(list)
{
  var result = [ ];

  for (var i=0; i<list.length; i++)
  {
     var item = 'item' + list[i];
     result.push( makeLogger(i, item) );
  }
  return result;

  // Capture the parameters for future logging
  function makeLogger(i, item)
  {
    return function() {
        console.log( item + ' ' + list[i]);   
    }; 
  }  
}

function foo() 
{
  var list = init([1,2,3]);
  for ( var j=0; j<list.length; j++)
  {
    list[j]();
  }
}

foo();

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