JavaScript IIFE How IIFE work in JavaScript

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

The General Syntax:

(function(){

/ / . . .

})();

Syntax explained:

  • It is enclosed within a grouping operator() as an anonymous function with its own lexical scope.
  • This prevents outside access and also polluting the global scope.
  • The second part is an immediately invoked function expression () via which the JavaScript engine will directly interpret the function.

when you define a function or a variable, the JavaScript engine adds the function to the global object.

There are two problems with this:

  • JavaScript engine will only release the memory allocated for them until when the global object loses the scope.
  • It will likely cause name collisions.

One way to prevent the functions and variables from polluting the global object is to use immediately invoked function expressions (IIFE).

It is called an immediately invoked function expression (IIFE) because the function is created as an expression and is executed immediately.

Leave a Reply

Your email address will not be published. Required fields are marked *