DEV Community

Katherine Kelly
Katherine Kelly

Posted on

Spare the (Global) Air

When I first learned JavaScript, I got into a pattern of keeping my frequently-used variables and invoked function calls at the top of my file. Sure, my code worked, but I couldn't help but wonder what the implications were of those variables and method calls just hanging out there in space and whether there was a better way to structure my code.

Yes, there is a much better way to structure your code! If you’re a newb like me, let me introduce you to IIFE, an immediately invoked function expression affectionately nicknamed "iffy."

IIFE (Immediately Invoked Function Expression)

According to MDN Web Docs, an IIFE is a JavaScript function that runs as soon as it is defined. A common way to write it is:

(function () {
  // do cool stuff here...
})();

As you may have noticed, it’s an anonymous function wrapped in parenthesis and has a second set of parenthesis at the end. By wrapping the anonymous function in parenthesis, JavaScript will run it as a function expression, and not a function declaration. The second set of parenthesis will actually invoke the function immediately after it is defined.

Why You Should Use IIFEs

IIFEs are used to prevent the pollution of the global scope. Once I realized I was polluting my global scope with my inadvertent global variables and functions, I wanted to rein it in.

gif of bringing it in

Via GIPHY

By nesting my code within the IIFE, it not only cut down on the unnecessary bloat in my global environment, but it also safeguards my code. An IIFE creates a lexical scope that allows public access to methods while keeping variables defined within the function inaccessible. That’s some good privacy for those variables.

An optional addition to your IIFE is to include a semicolon at the beginning. This makes it more defensive in case a previously included JavaScript file does not terminate with a semicolon.

;(function () {
  // do cool stuff here...
})();

So be the catalytic converter (better yet, take public transportation or walk) to your JavaScript code and keep pollutants that you can out of the air!

Resources
IIFE
Immediately invoked function expression
JavaScript: What the heck is an Immediately-Invoked Function Expression?

Top comments (0)