Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Private Variables with IIFEs

    Tyler ClarkTyler Clark
    javascriptJavaScript

    An IIFE (immediately invoked function expression) is when a function is called immediately after it is defined. These functions are defined and called once and are not accessed by other functions, variables, or from the global namespace. This is because it uses the grouping operator to make these function declarations an expression. Because of this one time invocation and lack of accessibility, we can use their function scope to hide variables from being access from anywhere else.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: It immediately invokes function expressions or functions that are called right after they are declared. Normally when functions are declared, they're put on the global space like the window object. However, IIFEs, for sure, are not.

    The magic behind an IIFE is the initial wrapping of the function with the open/close parens. This is called the grouping operator. This makes it an expression because the grouping operator returns whatever is inside of the parens.

    Again, because it is an expression, you cannot access the IIFE in the global namespace. This includes any variable or any other function defined within the IIFE. We have no access to these variables from outside. This is because const A and anything else we define within this function is scoped only to this function findName. Since we can access findName from the global scope, it acts like a private variable.

    We see IIFEs used a lot when working on code that is private and when we don't want other scopes to access its state. This is the syntax for creating an IIFE using an arrow function. All the same scoping rules apply, which again means we can't access anything inside of the arrow function because of the function's block scope and its inability to be accessed.