JavaScript IIFEs

The Udemy course, JavaScript: Understanding the Weird Parts, includes 85 lectures. In lecture 45 I finally encountered something meaningfully new, IIFEs, or Immediately Invoked Function Expressions. This construction is unique to JavaScript in an explicit sense, though there is mention that another language has a similar feature. Their purpose is essentially to manage scope (or namespaces) and this comes up in two different ways.

One involves encapsulating a complex calculation in the global scope to keep it separate from inline code. This involves writing a function as an expression and without a name, and then burying it in parentheses (other syntaxes are possible) to establish the new scope. The encapsulated function may take parameters supplied to the function in their own parenthesized list, and has to return a result, perform an action, or leave some other side-effect in a global variable. The nice part is that within this temporary and protected scope you can declare “local” variables without having to worry about collisions with named variables in other scopes (mostly the global scope).

The other way involves encapsulating the code in an entire file within parentheses, which puts all its code and variable names in a separate scope and namespace. A lot of frameworks are apparently distributed in this form and the contents are accessed by declaring a local (global) variable and setting it to the contents of the external file, so everything in it can be addressed as localVar.anythingintheframework.

This can be done just as easily with a traditional function, at least for inline code at the global level.

Like many things in JavaScript it’ll take me a while to really grok this formation, the need for it, and its implications. I understand why it works the way it does in the context the course is explaining (quite well, I might add) but why it’s needed is a different question. This is just my initial understanding and I’ll have to do more digging around. Not every resource describes things quite the same way at first blush, though obviously they are all getting at the same underlying truth.

This entry was posted in Software and tagged . Bookmark the permalink.

Leave a Reply