Question:
The first time I encountered closures and not knowing what it was, I tried to syntactically understand what was happening in the code of the form: (function(){})(). It is known that the construction "()" is a function call. There was a question about the first parentheses
Later, imbued with the topic, the question of the first parentheses did not stop bothering me. Why are they needed if everything works without them?
At the same time, I have not seen a single example in articles about closures without the use of the first parentheses.
A classic example of a closure in JavaScript:
buttons[i].onclick = (function(a){
return function(){ console.log(a);}
})(i)
without the first brackets:
buttons[i].onclick = function(a){
return function(){ console.log(a);}
}(i)
What for in all examples these, it turns out superfluous, syntactic elements?
Answer:
The function
keyword in js can be used in two contexts – a function declaration context and an expression context, where this word creates an anonymous function.
If the line starts with the word function
, then this is a function declaration. With such a function, nothing can be done immediately (for example, called), in addition, it must have a name.
function (a) { console.log(a) } (5) // Ошибка
Therefore, such a function is wrapped in something:
+function (a) { console.log(a) } (5) // 5
!function (a) { console.log(a) } (5) // 5
~function (a) { console.log(a) } (5) // 5
(function (a) { console.log(a) }) (5) // 5
(function (a) { console.log(a) } (5)) // 5
If the word function
is not at the beginning of the line, then you don’t need to do anything, everything will work fine:
var a = function (a) { return 5 } (5)