I'm reading the book secrets of the js ninja
, and very often I saw code like this
(function(){
something here;
})();
Why do we need to enclose the function within parentheses and why do we add one more pair of parentheses after that?
Parenthesis are used in an arrow function to return an object. Parenthesis are used to group multiline of codes on JavaScript return statement so to prevent semicolon inserted automatically in the wrong place.
Parentheses have multiple functions relating to functions and structures. They are used to contain a list of parameters passed to functions and control structures and they are used to group expressions to control the order of execution.
Therefore, you have to put brackets after the function name to declare the arguments. Brackets used for passing argument When you want to declare a function brackets used whenever you pass arguments or not. That is a part of function declaration. So that is same for the main function also.
This
(function(){
alert('hello');
})();
although it is a function is it called automatically so you dont/can't call it manually
These can be useful for for
loops like so
This will fail because i would be equal to 9 after 5 seconds
for(var i = 0; i < 10; i++) {
window.setTimeout(function(){
console.log(i);
}, 5000)
}
So you could do this
for(var i = 0; i < 10; i++) {
(function(a){
window.setTimeout(function(){
console.log(a);
}, 5000)
})(i);
}
Also good for creating a "private" scope like this
(function(){
var test = 'hello';
console.log( test ); // 'hello'
}());
console.log( test ); // 'undefined'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With