Skip to main content

IIFE

Immediatley Invoked Function Expression is a function that runs as soon as it is defined.

Syntax

(function () {
// your code here
})();
  • as it covered with braces, it consider as function expression instead function statement.

Function Expression also works with IIFE

const sum = (function () {
return 10 + 20;
})();
console.log(sum);

sum will be 30, don't need call the function

  • it can be used to create private function/variable
(function show(name) {
var msg = `Hello ${name}`;
console.log(msg);
})("Masum Billah");
  • you can't use show() neither msg outside.
  • it's very easy to create private function/variable with ES6s let and const, just declare it inside {}.