Interactive online courses HTML Academy
2026-03-09 14:11 Diff

Once we learn about scopes and closures, we will return to our assignment. What has happened to our code? Why doesn’t the program work the way that it is supposed to?

for (var i = 0; i < thumbnails.length; i++) { thumbnails[i].addEventListener('click', function () { fullPhoto.src = photos[i]; }); }

The handlers that we created use the counter value i. The difficulty lies in ensuring that the handlers are not triggered immediately. Their code is only executed at the time the event occurs. By the time the first click event is executed, the loop has fully completed, the counter reaches its maximum value of  5 , and the handler function takes this value. The loop does not create a separate scope. After all, it is not a function. Therefore, the value of i is found in the global scope, and so each handler accesses this value of 5. And we do not have a thumbnail with such an index or an element in the photos array, so no image is substituted.

How can we fix this problem? With closures, that’s how!

We will create a function that will take a thumbnail and its corresponding element from the photos array as parameters. And we will be able to add handlers inside this function. Then each handler will take values from its closure, from the parameters of the function where the handler is located.

Each handler has its own closure, so that values in the handlers will not be repeated, as was the case previously.

Let’s gradually improve our program so that it works correctly.