Search⌘ K

Solution Review: Closure, `setTimeout`, Scopes

Explore how JavaScript closures provide inner functions access to outer variables and how setTimeout interacts with the event loop and scope. Understand why asynchronous callbacks within loops print unexpected values due to closure and scope behavior, preparing you for related coding interview questions.

We'll cover the following...

Question: Solution review #

In the previous lesson, you were given 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);
}

For the code above, you were asked the following question:

Explanation #

Let’s start by running the code below:

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);
}

Before we get into the details of why the output ...