const IIFE = () => {
  console.log('Immediately Invoked Function Expression');
};

JavaScript has functions, just like any programming language and I will show you a rarely used method of calling a function. Some major libraries use it.

This is a simple function declaration and calling.

function multiply(a, b) {
  console.log(a * b);
}

multiply(2, 5); // 10

IIFE’s are functions, but they are anonymous functions. From the example above, we declare a new multiply function and call it afterwards.

IIFE’s do not work that way. They are functions first but anonymous, then immediately after being declared, they are called. So there is no need for a function name.

Syntax for an IIFE:

([function(parameters)])(arguments)

Example:

(function (a, b) {
  console.log(a * b);
})(2, 5); // 10

The parameters can be ommited if the function does not require one.

(function () {
  console.log('Thank you for reading my post.');
})();

You can also assign an IIFE to a variable and use the variable later in your code.

const product = (function (a, b) {
  return a * b;
})(2, 5);

console.log(product);

The difference between an IIFE and a normal function declaration is that for a function declaration, you can call the function and use it later in your code, anytime you want, but an IIFE is a type of function declaration which is called immediately and used immediately after.

You can try IIFE’s in your code now. It is very handy.