js closure trick

by Roman Fedytskyi

HTML

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div>
    <button class="btn_1">one</button>
    <button class="btn_2">two</button>
    <button class="btn_3">three</button>
    <button class="btn_4">four</button>
    <button class="btn_5">five</button>
    <button class="btn_6">six</button>
    <button class="btn_7">seven</button>
    <button class="btn_8">eight</button>
    <button class="btn_9">nine</button>
    <button class="btn_10">ten</button>
</div>

JavaScript

//code below is expected to write the number of link into the console
//try to understand the issue before giving a solution



for (let i = 1; i <= 10; i++) {
	$('.btn_' + i).on('click', function() {
        alert(i);
    });
}

for (var i = 1; i <= 10; i++) {
	(function(inner) {
  $('.btn_' + i).on('click', function() {
        alert(inner);
    })
  }(i));
}