Immediately Invoked Function Expression (IIFE) In JavaScript

  • An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. The syntax for defining an IIFE involves wrapping a function expression in parentheses and then immediately invoking it using an additional set of parentheses.
  • Here's an example of an IIFE:

    (function () {
        // code to be executed immediately
    })();

  • In this example, the function is defined and immediately invoked. The code inside the function is executed as soon as the script is loaded.
  • IIFEs are commonly used to create a new scope for variables, so they don't conflict with other code on the page. This is especially useful when working with JavaScript libraries that may define their own global variables. By wrapping your code in an IIFE, you can ensure that your variables are kept separate and won't conflict with other code.
  • Another benefit of IIFEs is that they can be used to create private variables and functions. Since the function is executed immediately and only the return value is accessible, any variables or functions defined inside the IIFE will not be accessible from outside the function.
  • Overall, IIFEs provide a way to encapsulate code and avoid conflicts with other code on the page. They can also be used to create private variables and functions, which can be useful in certain situations.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...