Use Immediately-Invoked Function Expressions
An immediately-invoked function expression (IIFE) is an anonymous function that runs immediately when it is defined.
The format for such functions is
(function() {
// More code here...
}());
Note: The purpose of the outer parentheses is to get the JavaScript parser to treat this as an expression rather than a declaration. There are several other alternatives, but this is the most common.
As you can see, the function will be immediately called, since we have added () in the end of its deceleration.
The primary is advantage of IIFE is scoping.
In JavaScript only functions have scopes, thus an IIFE has it's own scope and declarations within it won't affect the global scope.
For this reason, it is very common to wrap libraries and modules with IIFE.
Written by Shay Ben Moshe
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Shayfalador
Authors
shaybenmoshe
13.17K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#