The IIFE Interview Question

Find other ways to solve the IIFE interview question shown in the previous lesson. We'll tie together concepts we covered earlier in the course.

We'll cover the following...

Recap

In the previous lesson, we introduced an interview question. We want the following code to print out:

0
1
2
3
4

We want a 1-second pause in between these printouts. Will this code result in this printout? If not, what will it print? What changes can we make in order to make it work as expected?

Press + to interact
for (var i = 0; i < 5; i++) { // We are explicitly using `var` for a reason
const time = i * 1000;
setTimeout(function() {console.log(i);}, time);
}

We gave one solution.

Press + to interact
for (var i = 0; i < 5; i++) {
(function(num) {
const time = num * 1000;
setTimeout(function() {console.log(num);}, time);
})(i);
}

With our knowledge of JavaScript, however, there are multiple ways to solve this problem. We don’t need to use an IIFE. Let’s discuss a couple more solutions to revisit some concepts and solidify our knowledge.

let

This is one of the simplest ways to solve the problem without using an IIFE.

Press + to interact
for (let i = 0; i < 5; i++) { // Using `let`
const time = i * 1000;
setTimeout(function() {console.log(i);}, time);
}

All we ...

Access this course and 1400+ top-rated courses and projects.