Syntax error What is the purpose of wrapping whole JavaScript files in anonymous functions?

What is the purpose of wrapping whole JavaScript files in anonymous functions?



The purpose of wrapping is to a namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.

Syntax

Here’s 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: 2020-06-12T08:58:55+05:30

964 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements