MyHeritage interview question

Closure problem: function addButtons(numButtons) { for (var i = 0; i < numButtons; i++) { var button = document.createElement('input'); button.type = 'button'; button.value = 'Button ' + (i + 1); button.oncl1ck = function() { alert['Button ' + (i + 1) + ' clicked'); }; document.body.appendChild(button); document.body.appendChild(document.createElement('br')); } } window.onl0ad = function() { addButtons(5); }; when clicking either button (1-5) will print "Button 5 Clicked",

Interview Answer

Anonymous

30 Jun 2016

//ES6 solution for (let i = 0; i < numButtons; i++) { . . } //Closure solution button.oncl1ck = function(buttonIndex) { return function() { alert['Button ' + (buttonIndex + 1) + ' clicked'); }; }(i);