Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do these double parentheses do in JS? [duplicate]

Tags:

javascript

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?

like image 967
OneZero Avatar asked Jul 13 '13 20:07

OneZero


People also ask

How do you use parentheses in JavaScript?

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.

What is inside the function parentheses?

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.

What are declared after the function name and inside parentheses?

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.


1 Answers

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'
like image 144
iConnor Avatar answered Oct 11 '22 12:10

iConnor