Javascript Function Closure used in for loop

Description

Javascript Function Closure used in for loop


let myArray = ["Apple", "Car", "Tree", "Castle"];
let closureArray = new Array();

function writeItem(word) {
  return function() {
    console.log(word + "<br />");
  }/*from   w w  w  .  j  a v a2  s .  co m*/
}

// Loop through myArray and create a closure for each that outputs that item
for (let i = 0; i < myArray.length; i++) {
  let theItem = myArray[i];
  closureArray[i] = writeItem(theItem);
}

// Loop through the closures and execute each one.
for (let i = 0; i < closureArray.length; i++) {
  closureArray[i]();
}



PreviousNext

Related