Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

IIFE (Immediately invoked function expression). Can any explain me the difference between the code below?

As per I know while executing the for loop the condition checked first and then the block code will be executed and after executing block code then only the condition checked again. I am not getting how the code in the first block is displaying 5 all the times and how the IIFE solved the problem.

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

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

1st block OUTPUT : 5,5,5,5,5 There is a time gap between each value display

2nd block OUTPUT : 0, 1, 2, 3, 4 There is a time gap between each value display

1 Answer

Steven Parker
Steven Parker
243,160 Points

The IIFE provides an execution context and a scope for the variables in it. In the first example, there is only one "i", and the value in it increase to 5 before the loop ends. Then, as each callback runs, it uses that value (5).

But in the second example, each "num" gets its own context, so the value that will be used when the callback runs does not change within the individual "setTimeout" callbacks.