Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Basic JavaScript

JS TutorialJS SyntaxJS VariablesJS OperatorsJS If ConditionsJS LoopsJS StringsJS NumbersJS FunctionsJS ObjectsJS DatesJS ArraysJS Typed ArraysJS SetsJS MapsJS MathJS RegExpJS Data TypesJS ErrorsJS EventsJS ProgrammingJS ReferencesJS Versions

JS Advanced

JS FunctionsJS ObjectsJS ClassesJS IterationsJS AsynchronousJS ModulesJS Meta & ProxyJS HTML DOMJS WindowsJS Web APIJS AJAXJS JSONJS jQueryJS GraphicsJS ExamplesJS Reference


Immediately Invoked Expression

JavaScript IIFE

AnIIFE (Immediately Invoked Function Expression) is a function that runsimmediately after it is defined.

IIFEs where often used for encapsulation, especiallybefore ES6 modules existed.

Self-Invoking Functions

Function expressions can be madeself-invoking.

A self-invoking expression isinvoked (started) automatically, without being called.

Function expressions will execute automatically if the expression is followed by ().

You have to add parentheses around the function to indicate that it is an expression:

Syntax

(function () {  // Code to run immediately})();
  • The function is wrapped inparentheses to turn it into anexpression.
  • The final() executes the function immediately.

Note

You can only self-invoke a function expression.

You can not self-invoke a function declaration.


When Use an IIFE?

Although ES6 let, const, and modules reduce the need for IIFEs, they are still useful when:

  • You want private scope in a browser script file
  • You need initialization code that should run immediately
  • Working with older code that rely on them

Avoid Polluting the Global Scope

Variables inside an IIFE cannot be accessed from outside.

Example

(function () {
  let hidden = 42;
})();

let result = hideen; // ⛔ Error: hidden is not defined

Simple IIFE

Example

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

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


IIFE with Parameters

Example

(function (name) {
  let text = "Hello " + name;
})("John Doe");
Try it Yourself »

Arrow Function IIFE

Example

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

Arrow Function IIFE with Parameter

Example

((name) => {
  let text = "Hello " + name;
})("John Doe");
Try it Yourself »

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();
Try it Yourself »

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?

For self-recursion functions (calling itself repeatedly):

Example

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

Notes

IIFEs were heavily used before ES6 introducedlet,const, andModules.

They are still useful for:

  • Running setup code
  • Creating private variables
  • Avoiding global scope pollution


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp