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.
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?
for (var i = 0; i < 5; i++) { // We are explicitly using `var` for a reasonconst time = i * 1000;setTimeout(function() {console.log(i);}, time);}
We gave one solution.
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.
for (let i = 0; i < 5; i++) { // Using `let`const time = i * 1000;setTimeout(function() {console.log(i);}, time);}
All we ...
Get hands-on with 1400+ tech skills courses.