Check out a free preview of the full Getting Started with JavaScript, v2 course

The "IIFEs" Lesson is part of the full, Getting Started with JavaScript, v2 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle discusses when it is beneficial to use the IIFE pattern to create immediately invoked function expressions.


Transcript from the "IIFEs" Lesson

>> Kyle Simpson: Here's another example of function expressions. We call these IIFEs. I-I-F-E, which stands for Immediately Invoked Function Expression. You undoubtedly will have seen at least some of these in some code at some point because it's an extremely common pattern. What we see here is a function called anotherTeacher.

You'll notice that on line three to line six there's a wrapping set of parenthesis around that function. That's what makes it a function expression instead of the other form of function which we call a declaration. Here, it's a value. And then specifically, on line six is where it's getting executed.

That's the immediately invoked part, it's being executed immediately. After we describe that function expression as a value, it immediately invokes it. That's what makes it an IIFE. And the main end result of an IIFE, the main end result of running a function is that we get a new block of scope there.

There's a block of scope inside of that function anotherTeacher. So when I say var teacher equals Suzy on line four, I'm making a teacher variable inside of that function. I'm not overriding the one from line one. That allows us to encapsulate some of our behaviors and things so that they don't pollute other parts of the program.

We wouldn't want for line eight to print Suzy. We want for line eight to print Kyle. And the way that we protect that assignment on line four from changing it is that we wrap a function around it. That's at least one ways to do so. So IIFEs are a very common pattern, they've been sort of idiomatically around for more than a decade.

You see linked here in the slides a blog post back to 2010 from where this idea of IIFEs, immediately invoked function expressions, was kind of described. And they are typically used in places in our code where we need to collect a set of variables and protect them from encroaching upon an outer scope.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now