JSFiddle - React, Tailwind, and code Playground

HTML

<ul>
  <li><a href="#one">One</a></li>
  <li><a href="#two">Two</a></li>
  <li><a href="#three">Three</a></li>
  <li><a href="#four">Four</a></li>
</ul>

<button>Without closure</button>
<button>With closure</button>

JavaScript

var links = document.getElementsByTagName('a');
var alllinks = links.length;

function withoutclosure() {
  for (var i=0; i<alllinks; i++) {
    links[i].onclick = function() { alert(i); }
  }
}
function withclosure() {
  for (var i=0; i<alllinks; i++) {
    links[i].onclick = (function(j) {
      return function() {
        alert(j+1);
      }
    })(i);
  }
}

document.querySelectorAll('button')[0].onclick = withoutclosure;
document.querySelectorAll('button')[1].onclick = withclosure;