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

What is an Immediately-Invoked Function Expression (IIFE) in JavaScript?

Susan Sarandon
Release: 2025-01-04 00:53:42
Original
595 people have browsed it

What is an Immediately-Invoked Function Expression (IIFE) in JavaScript?

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

The (function() { } )() construct, also known as an Immediately-Invoked Function Expression (IIFE), is a unique pattern used in JavaScript to define and execute functions immediately after their creation. Unlike event handlers, which are triggered by specific events, an IIFE executes as soon as it is encountered.

Syntax and Structure

An IIFE consists of two main parts:

  • Expression Wrapping: The first part involves wrapping a function expression in parentheses: (function() { } ). This defines a function but doesn't call it yet.
  • Immediate Invocation: To execute the function, an additional set of parentheses is added to the end: (function() { } )(). This portion calls the function immediately.

Explanation

The outer parentheses create an expression that includes the function definition. The inner parentheses, with no arguments, cause the function to execute automatically.

Benefits of IIFEs

IIFEs offer several advantages:

  • Namespace Privacy: Variables and functions inside an IIFE are scoped within the function, preventing them from polluting the global namespace.
  • Code Reusability: IIFEs can be used to modularize code, making it easier to reuse in different parts of the application.
  • Performance Optimization: By wrapping code in an IIFE, the parser can optimize it before execution.

Example

Consider this code block:

(function() {
  var myVariable = 'Hello';
  console.log(myVariable);
})();
Copy after login

When this code executes, the myVariable variable is only accessible within the IIFE. Outside the function, it remains undefined.

Distinction from document.onload

While IIFEs and document.onload may both involve immediate execution, they differ in purpose. document.onload is an event handler that waits for the DOM to load before executing its function. IIFEs, on the other hand, execute independent of any events and are used primarily for encapsulation and code reuse.

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

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