bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

Self-Invoking Functions

Immediately Invoked Function Expressions

An IIFE is short for an Immediately Invoked Function Expression .

An IIFE is a function that invokes itself when defined.

What Is an IIFE?

Normally, a function runs only when it is called.

An IIFE runs automatically when the JavaScript engine reads it (compiles it).

(function () {
 // Code to run immediately
})();

An IIFE function is defined and executed at the same time.

When is IIFE Used?

  • To create a private scope
  • To run setup code once
  • In older JavaScript code

Avoid Polluting the Global Scope

Everything inside an IIFE is private to that function.

Variables inside an IIFE cannot be accessed from outside.

Simple IIFE

Example

(function () {
  let text = "Hello! I called myself.";
})();

The function above is also called an anonymous self-invoking function (function without name).

How an IIFE Works

Function expressions can be made self-invoking .

A self-invoking function expression is invoked (started) automatically , without being called.

Function

function () {
 // Code to run
};

Parentheses around the function tell JavaScript to treat the function as an expression.

Expression

(function () {
 // Code to run
});

The function is wrapped in parentheses to turn it into an expression .

Final Syntax

(function () {
 // Code to run
})();

The final () executes the function immediately.

You can only self-invoke a function expression.

You can not self-invoke a function declaration.

IIFE with Parameters

You can pass arguments into an IIFE.

Example

(function (name) {
  let text = "Hello " + name;
})("John Doe");

IIFE with Return Value

An IIFE can return a value, which can be stored in a variable.

Example

let result = (function () {
 return 5 + 5;
})();

Arrow Function IIFE

Arrow functions can also be used as IIFEs.

Example

(() => {
  let text = "Hello! I called myself.";
})();

Arrow Function IIFE with Parameter

Example

((name) => {
  let text = "Hello " + name;
})("John Doe");

IIFE in Modern JavaScript

Today, JavaScript modules often replace the need for IIFEs. Modules have their own scope by default.

Example

<script type="module">
let x = 10;
</script>

The variable x is scoped to the module and not global.

Named Function Expression IIFE

You can give an IIFE a name:

Example

(function greet() {
 let text = "Hello! I called myself.";
})();
greet(); // ⛔ ReferenceError

But, the name greet exists only inside the function itself, not in the outer/global scope.

Why use a named IIFE?

Example

(function factorial(n) {
 if (n <= 1) return 1;
 return n * factorial(n - 1); // recursive call
})(5);

IIFE as a Module (Private Variables)

Example

const counter = (function () {
  let value = 0;
  return {
    increment() { value++; }, get() { return value; }
  };
})();
counter.increment();
let x = counter.get();

Self Invocing Functions were heavily used before ECMAScript 6

Today, JavaScript let , const , and modules have reduced the need for them.

But they can still be useful for:

  • Running setup code that should immediately
  • Creating private variables and private scope
  • Avoiding global scope pollution
  • Working with older JavaScript code that rely on them

When Not to Use IIFE

  • When using modern JavaScript modules
  • When simpler code is sufficient

Common Mistakes

  • Forgetting the Final Parentheses Without () , the function will not run.
  • Confusing IIFE with Normal Functions IIFEs cannot be called again.
  • Overusing IIFEs Modern JavaScript often does not need them.

Previous

JavaScript PlainYearMonth

Next

JavaScript PlainMonthDay

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

Immediately Invoked Function ExpressionsWhat Is an IIFE?When is IIFE Used?Avoid Polluting the Global ScopeSimple IIFEHow an IIFE WorksFunctionExpressionFinal SyntaxIIFE with ParametersIIFE with Return ValueArrow Function IIFEArrow Function IIFE with ParameterIIFE in Modern JavaScriptNamed Function Expression IIFEIIFE as a Module (Private Variables)When Not to Use IIFECommon Mistakes