176k views
3 votes
Consider the following code snippet:

for (var i = 0; i < 5; i++) {
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
btn.addEventListener('click', function(){ (i); });
.appendChild(btn);
}
(a) What gets logged to the console when the user clicks on "Button 4" and why?

(b) Provide one or more alternate implementations that will work as expected.

User Vicky P
by
8.2k points

1 Answer

6 votes

Final answer:

When the user clicks on 'Button 4', the number 5 will be logged to the console. This can be fixed by using the 'let' keyword instead of 'var' or by using an IIFE.

Step-by-step explanation:

(a) When the user clicks on 'Button 4', the number 5 will be logged to the console. This is because the variable 'i' is declared with the 'var' keyword, which creates a function-level scope. The event listener in the for loop creates a closure that captures the value of 'i' at the end of the loop. Therefore, when the button is clicked, the value of 'i' is already incremented to 5.

(b) One alternate implementation is to use the 'let' keyword instead of 'var' to declare the variable 'i'. The 'let' keyword creates a block-level scope, so each iteration of the loop will have its own separate 'i' variable. Another option is to use an Immediately Invoked Function Expression (IIFE) to create a new scope for each iteration of the loop.

User Whg
by
8.8k points