(function(){
// do something here
})();
In these 3 lines of code (one of them is actually a comment) there's a lot going on under the hood. Bellow I'll explain what is going on behind the scenes and why/when should we use it.
Self-executing functions are a way to allow the creation of an isolated scope for code that we want to execute right after it's parsed.
var a = 5;
function MyFunction(){
var a = 10;
return a;
}
console.log(MyFunction()); // prints 10
console.log(a); // prints 5
Scope itself is a complex topic that I'll cover in another article; for now, I'll keep it simple and restrict it to this example.
function MyFunction(){
// do something here
}
and an anonymous function is defined like this:
function(){
// do something here
}
As it shows above, you can call the
MyFunction() but you can't call the anonymous function because it has no name. What you can do instead is declare the anonymous function and assign it to a variable, like this:
var MyFunction = function(){
// do something here
}
In this case, the variable MyFunction will hold a function that you can call with
MyFunction(). All good until now? :)
(function(){
// do something here
})()
and here we are; we've created our
self-executing function!
(function($){
// do something here
// making sure that $ represents jQuery
})(jQuery)
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (2)
Commented:
Author
Commented:you're right, thanks!
I've added it to the article.
Cheers!
Alex