-1
for(i=0; i< 3; i++){
    (function(i){
        console.log(i)
    })(i);
}

I've encountered this and was wondering how it works (I understood the result, just want some deeper explanation on the (function(i){})(i) and what it's called. Thanks lots!!!

StuartLC
  • 104,537
  • 17
  • 209
  • 285
user2393426
  • 165
  • 1
  • 10

4 Answers4

1
(function(i){
    console.log(i)
})(i);

This is what is known as a self-executing anonymous function, or a function that you don't have to give a name. It's also executed immediately after being defined. If you look at the first set of parentheses, they wrap the function keyword, argument list, and function defintion, while the second set of parentheses are where you pass in your argument.

/* self-executing anonymous function definition */
(   function(i){
        console.log(i)
    }    
)

/* pass argument i into the anonymous function and execute */
(i);

I split this up a little more with whitespace so that it's easier to break it down visually.

Now, because the function parameter and the argument have the same name, the definition may be confusing to someone seeing this for the first time. So here's that same example, except let's just pass in an actual value into the function:

(function(i){
    console.log(i) // prints '5'
})(5);
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
1

The portion of code:

(function(i){
    console.log(i)
})(i);

is what's known as an IIFE (immediately-invoked function expression).

The important takeaway here is that in JavaScript, functions are first-class objects. To elaborate on this point, I could also have done the following:

var log = function(i) {
   console.log(i);
}

for(var i=0; i<3; i++){
   log(i);
}

In this example, I've stored the function as a variable and later called it using the function invocation operator ()

Returning to the original example, the surrounding parenthesis around the anonymous function really contains what I had stored in the log variable. The trailing parenthesis then invokes the anonymous function that was created inside parenthesis.

kaminari
  • 306
  • 1
  • 5
0
(function(i){})(i)

This is a self executing function. These are automatically evaluated inline to return a value. It's a nice feature of Javascript that it pays to understand. You can use them this way but they are really nice for creating Javascript Modules that scope and extend code.

jeremyjjbrown
  • 7,772
  • 5
  • 43
  • 55
  • *"These are automatically evaluated inline to return a value."* I'm not sure what you mean by "to return a value". – Felix Kling Feb 12 '14 at 03:43
0

For each iteration of the loop you are create and immediately calling an anonymous function with whatever the value of i is at the time of that specific iteration.

please not that this would work without you passing in any arguments because i is still in context when you call the function.

Mr. Smee
  • 968
  • 11
  • 28