IIFE | javascript

Summary of an IIFE

An IIFE stands for an immediately invoked function expression. In short, an iife is a function that gets turned into a function expression and gets immediately executed at runtime, once and only once by the javascript engine.

Break down of what an IIFE actually is

An iife can be broken down and understood with two main concepts.

Immediately invoked - means the function gets called right after it is created.

Function expression - means that you don't need to name that function. It is an anonymous function that is not hoisted. A function expression is a anonymous function that is attached to a variable. In the case of an iife, we don't need to attach it to a variable which is why it must be called immediately.

Syntax and Basic Example

There are many ways to write an iife. Below shows a few ways to this. In each case the syntax essentially turns the function into an expression which then immediately gets executed.

   
              // Variation 1: 
            (function(){
                const myName = 'Bob';
                console.log(myName);
            })();

            // Variation 2: 
            !function(){
                const myName = 'Anna';
                console.log(myName);
            }();

            // Variation 3: 
            void function (){
                const myName = 'Cambria';
                console.log(myName);
            }();

            // ** Reasons to use an iife **
            // Variables inside of it don't interfere with other global variables in our code.
            // It is a function that is immediatley executed 
            // It runs once an only once, unlike a regular function which can be called any number of times.
               

IIFE with Parameters

An iife can take parameters. This is a really handy pattern that let's you use an iife with arguments.

  
              (function myIIFE(greeting){
                const nameArr = ['Anna','Bob','Cambria'];
                nameArr.forEach(name => {
                        console.log(`${greeting} i'm ${name}!`);
                });
              })('Hello');
               

Variables inside an iife are not accesible to the outside world. They are private variables only accessible to the iife and destroyed once the iife has executed.

Count Down Function with an IIFE

Here is a slightly less trivial example.

  
        // count down function with iife
        (function myIIFE(greeting,startNumber,endNumber, timer = 1000){
             const mySetInterval = setInterval(()=>{

                    if(startNumber === endNumber){
                        console.log(`${greeting}`);
                        window.clearInterval(mySetInterval);
                    }
                    else{
                        console.log(`time until launch:${startNumber}`);
                    }

            startNumber--;
            },timer);

        })('blast off',3,0,500);
               

This iife has three required parameters and one optional parameter, timer, with a default value of 1000.

SetInterval and clearInterval is used to call the function a fixed number of times after a set delay

Once the startNumber is equal to the endNumber, we use clearInterval to stop the execution after the greeting is logged


Dash-Intel is a Power BI and Tableau resource site for data visualization and building BI dashboards.

Data Analyst & Consultant

Copyright 2015-2023 Dash-Intel.com Terms