bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

Self-Invoking Functions

Concept visual

Self-Invoking Functions

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

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).

Example

(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.

Examples

(function () {
let x = 10;
})();

// x is not accessible here

(function () {
let hidden = 42;
})();
let result = hidden; // ⛔ Error: hidden is not defined

Simple IIFE

Example

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

Formula

The function above is also called an anonymous self - invoking function

(function without name).

How an IIFE Works

Formula

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. Function expressions will execute automatically if the expression is followed by ().

Final Syntax

(function () {

// Code to run

})();

The final

() executes the function immediately.

Formula

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

Previous

JavaScript PlainYearMonth

Next

JavaScript PlainMonthDay