This is one of those things you probably saw and didn't even know how to google. I didn't know what it's called so I had to ask on stackoverflow.
So you define an anonymous function and call it right away:
(function(){
// do this right now
console.log("Look at me, I'm running");
})();
This will be the equivalent of naming a function and calling it right away:
function run() {
console.log("Look at me, I'm running");
}
run(); // the call;
You might find some slight variations in different code. Sometimes it is the end parentheses are inside the main ones:
(function(){}());
Or the it starts with an exclamation point:
!function(){}();
All that matters is that the content of the function is executed right away.
Using a self invoking function
You might ask your self why would you ever need to use that. First of all the cool kids use it... ok we don't care about that, but there are some actual practical uses for it.
In JavaScript, every function creates a scope. Meaning, variables defined using var
inside a function cannot be accessed outside of it. If you were to add two JavaScript files to your page. All the variables defined globally inside the first file will automatically be available in the second. (actually the ones from the second file will also be available to the first file). This pollutes the global namespace.
By using globals it makes it much easier to overwrite a value by mistake which makes your application very hard to debug.
By using globals, there are higher chances of making your variable names collide. You can overwrite a value by mistake.
By surrounding sections of your application with a anonymous function, you create a scope where all the variables defined exist only in this function. You may choose to make some variables accessible outside but this will be your choice not the default behavior.
You can use it to initialize some values required to create an object also. I recently was looking for a way to define functions dynamically instead of checking if the browser supports a feature every time I call the function. I posted my solution as dynamic function definition, here is how it works:
var Handler = (function (){
var on = "",
attach = "attachEvent",
detach = "detachEvent";
if(window.attachEvent){
on = "on";
}else {
attach = "addEventListener";
detach = "removeEventListener";
}
return {
addEvent: function (elem,event,func){
elem[attach](on+event,func,false); // bubbling will be ignored in IE
},
removeEvent : function (elem,event,func){
elem[detach](on+event,func);
}
};
})();
Note that (on,attach, and detach) are not available outside this context. Only the Handler object can access them internaly through addEvent() and removeEvent() Think of them as private variables.
So in conclusion, self invoking anonymous functions are function that are called immidiately as they are defined. The advantage of using them is that they create a scope and prevent global namespace polution. They can also be used to initialize values before an object is created.
If you find some cool methods of using self invoked anonymous functions, don't forget to share it with us :)
Sign up for the Newsletter.
Comments(3)
edward robertson :
hi! Diallo, thanks for the tips, I do highly appreciate ur website...
Harshita :
Very crisp and to the point
Ronald DeSantis :
The problem of preventing variable definitions from polluting the global name space is solved by using "let" instead of "var". Use "let" and then you only need to put brackets around your block to keep variable definitions confined to block scope. See documentation.
Let's hear your thoughts