DEV Community

Cover image for IIFE's (Immediately-Invoked Function Expressions) in JavaScript Explained in 3 Minutes
Gabe Romualdo
Gabe Romualdo

Posted on • Updated on • Originally published at xtrp.io

IIFE's (Immediately-Invoked Function Expressions) in JavaScript Explained in 3 Minutes

JavaScript, like many programming languages, has implied global variables: variables which can be accessed by any function, anywhere, after they have been declared and defined, without specifying that the variable is global. For example:

// a global variable
var exampleStr = "Hello, World!"

function exampleFunction(){
    console.log(exampleStr)
}

exampleFunction();

// --> logs "Hello, World!" (contents of exampleStr global variable)
Enter fullscreen mode Exit fullscreen mode

Here, a global variable was defined with the value of "Hello, World!", and the function that was called had access to that variable and logged it to the console.

Global variables may be useful for smaller sites and code examples like this one, but they can cause problems in larger-scale projects and web apps.

One of the main reasons why globals can be harmful is variable naming collisions, which occur when a function creates or references a variable whose name has already been taken by a different variable that is a global.

In this example, the variable name which has a collision is name:

var name = "Fred"

function myFunction(){
    // intended to create variable, but changed global instead
    name = "John"

    // "John"
    console.log(name);
}

// "John", not "Fred"
console.log(name);
Enter fullscreen mode Exit fullscreen mode

While this is a very basic example, in programs with lots of JavaScript code, globals can become very hard to keep track of and cause serious unexpected problems which can be extremely hard to debug.

For example, Rasmus Lerdorf, the creator of the PHP programming language, worked at a company which had a very complicated bug involving globals and collisions. In order to find the bug, he printed out thousands of lines of code in paper and highlighted them until he found two globals with the same name colliding with each other, in completely unrelated places in the code. If you would like, you can hear more about this at his talk about 25 years of PHP.

IIFE's Help Fix the Globals Problem

Globals are frequently created because of code that is in the global scope, not in functions, whether those functions are explicitly defined, or used in DOM events or wrapped in a statement like setTimeout() or setInterval.

IIFEs (or Immediately-Invoked Function Expressions) allow for JavaScript code to be written within a function, but immediately call that function. All code within IIFEs should not pollute the global scope or create any globals.

Written with (function(){})() or (()=>{})()

IIFEs are written by wrapping a function in parentheses, and then calling that function like normal with ();.

Here is an example of a program without an IIFE, which pollutes the global scope:

Program Example (with IIFE)

Now, with an IIFE:

Program Example (without IIFE)

With the introduction of ES6 Arrow Functions, IIFE's can be further shortened like this:

// Without ES6:
(function(){

})();

// With ES6:
(()=>{

})();
Enter fullscreen mode Exit fullscreen mode

When to Use IIFEs

In many more complex programs and web apps, it can be helpful to eliminate global variables altogether. In that case, there would be little to no global code defined — code would be defined in functions and IIFEs.

In fact, it is very common to not use global variables altogether, and JavaScript has a special literal called use strict to prevent the use of global variables and throw errors if and when they are created.

For smaller sites and scripts, I would personally simply recommend actively trying to use IIFEs whenever possible, and limiting global code. I personally do use global variables in some basic sites for brevity, but it's important to have a clear understanding of what your code's global scope looks like and what sorts of unexpected problems could occur based on that.

I hope you enjoyed this article and found IIFEs to be something you could use in future projects and scripts.

Thanks for scrolling.

— Gabriel Romualdo, February 29, 2020

Top comments (5)

Collapse
 
mathieuhuot profile image
Mathieu Huot

use strict to prevent the use of global variables

use strict prevents assigning a value to an undeclared variable which , in non strict mode, would create a global variable (instead of throwing an error). However, strict mode allows you to declare a variable in global scope hence creating a global variable.

Collapse
 
gaberomualdo profile image
Gabe Romualdo • Edited

While it can be useful to not have any variables declared on the global scope entirely, variable naming collisions should, to the best of my knowledge, only occur if a global variable has a value assigned to it. Thus, use strict prevents these collisions by preventing the assignment of variables in the global scope.

This is what I meant when I wrote “use strict to prevent the use of global variables”.

— Gabriel

Collapse
 
mathieuhuot profile image
Mathieu Huot

Hi Fred, I think your article is very well written and it made me review my knowledge about JavaScript strict mode, so thank you for that! Now, it might just be a wording thing but I wanted to clarify that use strict will not prevent the assignment of variables in the global scope, it will only prevent the assignment of undeclared variables.

'use strict';
//The assignment or reassignment of a declared variable will not throw an error.
let globalVariable = 'global value';
globalVariable = 'another value';
//This code will not throw an error.
Enter fullscreen mode Exit fullscreen mode
'use strict';
globalVariable = 'global value';
//This will throw -> ReferenceError: assignment to undeclared variable globalVariable
//Note that if you remove "use strict" it will not throw an error but create a global variable instead.
Enter fullscreen mode Exit fullscreen mode

Here's a reference to what I'm describing in the code block above : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Erreurs/Undeclared_var?utm_source=mozilla&utm_medium=firefox-console-errors&utm_campaign=default

You're right that because use strict is preventing the accidental creation of global variables, it reduces the risk of name collision although it doesn't prevent the assignment of a declared variable, global or not. Again, thank you for the learning opportunity!

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

Oh really? I have assigned script-level variables the initial value of undefined with the intent of initializing them fully inside a later function call, in strict mode, which works just fine. To minimize the opportunity for conflicts, any function-scope variables use one of the ES5 keywords for this purpose in their declarations. Combined with a linter enforcing the rules, I make it as easy as possible to avoid trouble and detect the cause if it happens anyway.

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

I first got exposed to the IIFE idea via jQuery. Glad to hear regular JavaScript supports it! I can't think of any immediate uses, but I'm sure there will be some later.