4

Difference between the two functions:

(function($){
  console.log($);
}("test"));

(function($){
  console.log($);
})("test");

I've tried it out on the web console and pressed 'Run'. They return the same thing. What exactly is the difference with the change of parenthesis location?

I am assuming that the second one is run immediately, right?

Teej
  • 12,764
  • 9
  • 72
  • 93
  • 1
    How did you come to think there was a difference? – Matti Virkkunen Feb 16 '12 at 06:36
  • 1
    See also: http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions, http://stackoverflow.com/questions/3783007/is-there-a-difference-between-function-and-function, etc. – nnnnnn Feb 16 '12 at 07:00

3 Answers3

2

The two snippets are identical; neither function returns a value and both log their argument to the console. Similarly, both anonymous functions are called with the argument "test".

The only difference is in syntax, regarding the grouping of the function definition vs its application to its arguments. The first function groups the function definition along with the () operator, whereas the second function groups the function definition separately from its application.

Ultimately there is no semantic difference. Both snippets contain an anonymous function which logs its argument and is then called with the argument "test".

maerics
  • 151,642
  • 46
  • 269
  • 291
2

The only difference I can think of is if you assign a variable to a function inside the first set of parentheses, you will get different results, depending on the grouping.

var test;

(test = function(arg) {
  console.log(arg)
})('I am the argument!')

That works as expected: It assigns 'test' to the function, then runs it once with the argument in the second set of parentheses. It's the same as setting test, then running it with test('I am the argument!')

But how about the other way?

var test;

(test = function(arg) {
  console.log(arg)
}('I am the argument!'))

test is undefined! Why? Because when you put the parentheses right next to the function, it invokes the function before it then assigns it to the variable. If you wrap the assignment in parentheses then run it (example 1) then you're good to go.

Kevin McTigue
  • 3,503
  • 2
  • 18
  • 22
1

There is absolutely no difference.

In first case you give "test" value to your function without scopes and there isn't making any difference. In both ways it will working in same way.

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123