IIFE’s 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)

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);

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:
(()=>{

})();

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: see JavaScript use strict Explained in 2 Minutes.

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.

— Fred Adams, February 29, 2020



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *