Regular function declaration looks like this:
function FuncName() { doSomething(); }
Then you can call this function like this:
FuncName();
Anonymous functions are very similar:
var FuncName = function YouCanEvenPutANameHereAndItWillBeIgnored() { doSomething(); }
If the syntax for regular functions and anonymous functions is identical, then how does JS distinguish them? It deduces what you mean from context. That's why this Instantly Invoked Function Expression won't work:
function(s) { console.log(s); } ('abc');
JS parser reads it from left. The line starts with function
, so JS guesses it's a regular function declaration and expects it to end with }
. There's ('abc')
after the function, though, and JS throws an error.
To fix it, you have to trick JS into parsing that function as an anonymous function. To do that you have to make it part of an expression. The most popular way is this:
(function(s) { console.log(s); }) ('abc');
There are other ways, though. They are less readable, but they work too.
( function(s) { console.log(s); } ('abc') );
+function(s) { console.log(s); } ('abc');
-function(s) { console.log(s); } ('abc');
1 * function(s) { console.log(s); } ('abc');
In your case the function is already a part of an expression, so there's no need to add parentheses.