Transcript from the "IFFEs" 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.
[00:00:21] 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.
[00:00:40] 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.
[00:00:59] 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.
[00:01:20] 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.
[00:01:41] 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.