Search⌘ K

Solution Review: Closure, `setTimeout`, IIFE

Explore how closures, setTimeout, and IIFE work together in JavaScript loops. Learn to identify and fix common mistakes with variable scoping and asynchronous callbacks to prepare for interview questions effectively.

We'll cover the following...

Question: Solution review #

Explanation #

You were asked to choose the codes that will give the correct output for the following code:

Javascript (babel-node)
const array = [5, 11, 18, 25];
for (var i = 0; i < array.length; i++) {
setTimeout(function() {
console.log('Element: ' + array[i] + ', at index: ' + i);
}, 3000);
}

Let’s start by going through each option one-by-one.

Option A: Correct.

Run the code below:

Javascript (babel-node)
const array = [5, 11, 18, 25];
for (let i = 0; i < array.length; i++) {
setTimeout(function() {
console.log('Element: ' + array[i] + ', at index: ' + i);
}, 3000);
}

As you can see, it gives the correct answer. The only modification you need to make is declaring the iterator i using the keyword let rather than var. This fix makes use of ES6. Changing var to let changes the implementation so that the value of i ...