"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Immediately Invoked Function Expression (IIFE)

Immediately Invoked Function Expression (IIFE)

Published on 2024-11-07
Browse:855

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);
})();

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!

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.

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

Release Statement This article is reproduced at: https://dev.to/pranavbakare/immediately-invoked-function-expression-iife-3m1l?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3