Search⌘ K
AI Features

The IIFE Interview Question

Explore multiple solutions to a common JavaScript interview question involving loops and timing. Understand how IIFEs, let keyword scoping, and block scopes with brackets help manage variable scope and ensure expected output with delays. Gain insights into functional programming principles for cleaner, less error-prone code.

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?

Node.js
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.

Node.js
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.

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

All we did in this solution is change var to let. This works because of the ...