JavaScript Uses for Closures

Another awful lecture from Andrew Chalkley, he just can't explain things clearly

I'm confused with the buttonName example, his explanation is just not clear..

3 Answers

Michael Kobela
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Michael Kobela
Full Stack JavaScript Techdegree Graduate 19,535 Points

This is a difficult topic to understand at first, so let's cut Andrew a little slack. I have enjoyed his lectures. Let's see if I can clear this up. I copied the code and added the FOR loop for both examples. Please read my comments in the code and see if this helps.

function createHandler(name){
 // name will be first on loop i = 0;
 // name will be second on loop i = 1
 // name will be third on loop i = 2;
 // these are stored as a private member of this closure, for later use when the button is clicked

  return function(){
    // the  value of name in the closure is used, not the value in buttonName of the for loop
    console.log(name);
  }
}

// FOR loop with anonymous function
for(var i = 0; i < buttons.length; i += 1){
  var button = buttons[i];

  // each time through this loop the buttonName will update as follows:  first, second, third
  // so after the last loop, it will be buttonName will contain third

  var buttonName = button.innerHTML;

  // the button is clicked much later (asynchronous), so buttonName will always be third, since
  // that's the global scope of this function 
  // so when each button is clicked they will all see third, the last value placed in buttonName

button.addEventListener('click', function() {
    console.log(buttonName)
  }
}


// FOR loop with closure function
for(var i = 0, i < buttons,length; i += 1){
  var button = buttons[i];


  // each time through this loop the buttonName will update as follows:  first, second, third
  // so after the last loop, it will be buttonName will contain third
  // exactly the same as the other FOR loop above
  var buttonName = button.innerHTML;

   // MAGIC starts here
  // the button name is passed to the closure so three different closures are created
  // each closure will have a private member "name" (the parameter of this function)
  // that will hold the value passed so first closure will contain first, second closure 
  //second and so on. And the correct names will print when clicked.

  button.addEventListener('click', createrHandler(buttonName));
}

Hope this helps. Good luck.

Thank you Michael!

Thank you Michael!