Difference between these javascript functions

The difference between the two functions:

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

I tried this on the web console and clicked "Run." They return the same. What is the difference with changing the location of the brackets?

I guess the second one starts immediately, right?

+4
source share
3 answers

Two fragments are identical ; no function returns a value, and both write their argument to the console. Similarly, both anonymous functions are called with the argument "test" .

The only difference is the syntax regarding the grouping of the definition of the function and its application to its arguments. The first function groups the definition of the function together with the operator () , while the second function groups the definition of the function separately from its application.

Ultimately, there is no semantic difference. Both fragments contain an anonymous function that registers its argument and then is called with the argument "test".

+2
source

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

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

This works as expected: it assigns a β€œtest” function, then runs it once with an argument in the second set of parentheses. This is the same as setting up a test and then running it with test('I am the argument!')

But what about the other way?

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

test - undefined! What for? Because when you put parentheses next to a function, it calls the function before and then assigns it to a variable. If you complete the assignment in parentheses , then run it (example 1), then it will be convenient for you to go.

+2
source

Absolutely no difference .

In the first case, you give the "test" value of your function without areas and there is no difference. In both directions it will work the same.

+1
source

Source: https://habr.com/ru/post/1396777/


All Articles