What do these double parentheses do in JS?
javascript
Solution
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'
Problem
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?