Home > Web Front-end > JS Tutorial > What is an Immediately-Invoked Function Expression (IIFE) in JavaScript and How Does It Work?

What is an Immediately-Invoked Function Expression (IIFE) in JavaScript and How Does It Work?

Mary-Kate Olsen
Release: 2024-12-21 10:49:13
Original
987 people have browsed it

What is an Immediately-Invoked Function Expression (IIFE) in JavaScript and How Does It Work?

Understanding the (function() { } )() Construct in JavaScript

In JavaScript, a common construct is (function() { } )(). This pattern, known as an Immediately-Invoked Function Expression (IIFE), executes a function immediately upon its creation.

Purpose of IIFE

An IIFE encapsulates the variables and functions declared within it, making them inaccessible outside its scope. This prevents them from polluting the global namespace, where any variable or function declared outside a function is accessible globally.

The pattern is often used to:

  • Isolate and protect sensitive data and functions
  • Create private variables and methods within objects
  • Define event handlers for asynchronous events (such as window.onload)

Syntax and Execution

The IIFE consists of:

  • A function expression enclosed in parentheses: (function() { })
  • The function invocation operator () appended immediately after the closing parentheses of the function expression

When the IIFE is executed, the JavaScript interpreter parses the function expression, creates the function, and executes it immediately.

Example using IIFE

Consider the following code:

(function() {
  console.log("Executed immediately");
})();
Copy after login

In this example, the function within the IIFE is executed right after it is defined. It prints "Executed immediately" to the console at the time of execution.

Note:

Unlike event handlers such as document.onload, which respond to specific events, IIFEs are executed independently and do not rely on any external triggers. They provide a convenient way to encapsulate and execute code immediately, offering privacy and code organization benefits.

The above is the detailed content of What is an Immediately-Invoked Function Expression (IIFE) in JavaScript and How Does It Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template