Categories
Front End Development How to Javascript

How to immediately call a function in JavaScript (IIFE)

Sometimes you might want to run a function without ever having to call it. This is especially useful when you want to declare some global variables, but also keep them private, within a function. This article explains how you can immediately call a function in javascript.

What is an IIFE?

An Immediately Invoked Function Expression (IIFE) is a function is called as soon as it becomes available. You don’t need to call it with a function declaration or any other method. Many js libraries use them to keep their global variables under control and avoid conflicts with other scripts. It is also known as a Self Executing Anonymous Function, though we can also use named functions as we’ll see below.

When you include a third party javascript file on your website, an IIFE is usually called to run the script immediately – without you manually calling a function for it. This is how things like JQuery just work when you include the script on the page.

What an IIFE looks like

An IIFE is just a normal function wrapped in parenthesis, like so:

(function(){ ... })()

This will run as a function expression, rather than a function declaration. Appending the closing () will immediately invoke the expression. Function parameters can also be passed through here, such as:

(function(name, age))('jeff', 25)

Named IIFE’s can also be used like so:

(function hello(){...})()

IIFEs can also use arrow functions, be assigned to variables, and will still be immediately invoked:

const sayHello = (() => console.log('hello'))()
// output: hello

How an IIFE is used

As mentioned, there are many use cases for an immediately invoked function expression. For example, with jQuery, you can use it to prevent conflicts in your code. Such as if you have already used the $ assignment for some non-jquery code:

(($) => {
// add your jQuery code here
})(jQuery)

This code above is safely isolated/wrapped within the IIFE and so won’t affect your other scripts that may also use the $ assignment.

IIFEs can also be used to organise your code, so that it’s more maintainable, such as in this configuration:

const App = (function() {
  const config = {
    apiKey: "api-key-here"
  };
  
  return {
    getConfig: function() {
      return config
    }
  }
})()

console.log(App.getConfig().apiKey)

Conclusion

Variable scoping has become less of an issue with the addition of const and let, but using IIFE wisely can bring a lot of power and flexibility to your coding, and how to immediately call a function in javascript.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.