What is the purpose of a self-executing function in JavaScript?


The purpose of a self-executing is that those variables declared in the self-executing function are only available inside the self-executing function.

Variables declared in the self-executing function are, by default, only available to code within the self-executing function.

It is an immediately invoked function expression (IIFE). It is a function, which executes on creation.

Syntax

Here is the syntax −

(function() {
   // code
})();

As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression:

function(){...}

In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above.

Updated on: 12-Jun-2020

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements