Solution Review: Closure, `setTimeout`, IIFE
In this lesson, we will discuss the solution to the quiz in the previous lesson.
Question: Solution review #
Explanation #
You were asked to choose the codes that will give the correct output for the following code:
Press + to interact
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:
Press + to interact
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 ...
Access this course and 1400+ top-rated courses and projects.