Self-invoking functions explained line by line
I never knew it was possible to love a syntax but since, I fell in love with the self-invoking function which can be summarized like this : (function(){})(). Yes this is a valid syntax though it doesn’t do much in this form (it creates a function that does nothing and call it).
Some people call it self-invocation or self-executing but I don’t think it has an official name.
Let’s break it down
It will become clearer if I execute some code and write it on more than one line :
-
(
-
function() {
-
console.log("this line is called");
-
}
-
)
-
();
Line 1 : (
This first parenthesis is used as grouping operator. Read more here and here.
Line 2 : function() {
This create an anonymous function. I could write something like function doSomething() { but in the case of a self-invoking function, this is useless because the function is in its own little scope (line 1) and can’t be called from outside of it.
Line 3 : console.log(“this line is called”);
This is the code that will be invoked.
Line 4 : }
This clauses the function opened at line 2.
Line 5 : )
Clauses the parens opened at line 1.
Line 6 : ();
We call the function created at line 2 and returned within the scope from line 1 to 4.
Let’s write it in a more compact syntax :
-
(function() {
-
console.log("this line is called");
-
})()
See my post about using self-invoking functions to create namespaces.
Don’t forget to subscribe to my newsletter!