Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

IIFEs

IIFEs 12 min

javascript / IIFEs

Explore each scene at your own pace.

01 · IIFEs

IIFEs

IIFEs

An immediately invoked function expression defines a function expression and calls it immediately. Its local bindings belong to that invocation’s scope.

It creates a private working area and returns only what the caller needs.

See the mechanism

Walk through the modelIIFEsAuthored snapshots of the example; use Run below to test the code.
Statea function value is created
Defining instructions does not execute them.
1 of 3

Follow one example

javascript

The parentheses form an expression; the final () invokes it. prefix is local and does not become an outside binding. config receives the returned object. Modules and blocks often provide clearer isolation in modern code, but this pattern still appears in older scripts and one-time initialization.

Predict, change and check

Predict: If the final () is removed, is config the returned object or the function itself?

Test your explanation: Remove only the call parentheses and inspect typeof config. Restore them, then compare the technique with defining a named setup function and calling it once.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

A one-time invocation can establish private scope

An IIFE creates a function and invokes it immediately. Its result can be a value, an interface object or a closure that retains private bindings. Parentheses help distinguish an expression from a declaration in common forms; an IIFE is not a new module loader.

Use modules for ordinary file boundaries in a modern module project. An IIFE remains useful for a deliberately isolated initialization experiment. If its result includes a function, trace which outer binding that returned function retains rather than assuming all local state disappears the moment the initial invocation returns.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.