Private Variables with IIFEs

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

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.

Instructor: [00:00] 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.

[00:12] 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.

[00:26] 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.

[00:50] 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.

egghead
egghead
~ 35 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today