Home > Web Front-end > JS Tutorial > body text

Immediately Invoked Function Expression (IIFE)

WBOY
Release: 2024-09-03 12:09:31
Original
526 people have browsed it

Immediately Invoked Function Expression (IIFE)

An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. It is commonly used to avoid polluting the global scope or to create a private scope for variables.

Here’s a simple example of an IIFE:

(function() {
    var message = "Hello from IIFE!";
    console.log(message);
})();
Copy after login

Explanation:

  • The function is wrapped in parentheses: (function() { ... }). This makes the JavaScript engine treat it as an expression.
  • Immediately after the closing parenthesis of the function, another set of parentheses () is added to invoke the function immediately.
  • The function runs right after it is defined, logging "Hello from IIFE!" to the console.

Output:

Hello from IIFE!
Copy after login

Usage:

IIFEs are useful when you want to create a new scope, especially to protect variables from being accessed or modified outside of the function:

(function() {
    var counter = 0;  
// This counter is private and can't be accessed from outside

    function increment() {
        counter++;
        console.log(counter);
    }

    increment(); // Logs: 1
    increment(); // Logs: 2
})();

console.log(typeof counter); 
// Logs: "undefined", because `counter` is not accessible here.

Copy after login

This ensures that variables like counter remain private and are not accidentally modified or accessed from other parts of the code.

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

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!