title: Javascript - Function call only using last iteration of loop
body: <p>So here's my code:</p>
  
  <pre><code>for(var i = 0; i &lt; clickCell.length; i++) {
    clickCell[i].addEventListener("click", function(x) {
      showModal(i);
    });
  }
  
  function showModal(x) {
    switch (x) {
      case 1:
        image.style.background = "url('image1.jpg') center/cover no-repeat";
        break;
      case 2:
        image.style.background = "url('image2.jpg') center/cover no-repeat";
        break;
      case 3:
        image.style.background = "url('image3.jpg') center/cover no-repeat";
        break;
      default:
        break;
    }
    modal.style.display = "block";
  }
  </code></pre>
  
  <p>What I'm trying to do is display a modal with a different image based on what cell was clicked on in a table element. The for loop adds an event listener to each cell in the table. The showModal() function picks which image should be displayed based on which cell was clicked. My problem is that it seems only the last iteration of the loop counter i is being passed as an argument to showModal(). Now from what I've searched up, the solution seems to be something to do with closure. I've done some reading and I just can't seem to make the connection in my head. If someone could explain how I could get this piece of code to work and help me understand closure that would be greatly appreciated.</p>