bit of a silly question perhaps.
But I want to understand why the syntax on the self-executing function and the callback it has is so different to all the other JS syntax..
(function () {
})()
I just need to understand why its valid to encapsulate it with () I wouldn’t have guessed that to be valid, and then the extra () afterwards for the callback, (which just sits directly after it, I also wouldn’t have expected that to be valid.
Is anyone able to explain this to me?
The
function (...) {...}part is a function expression, that is, an expression that represents a function. The only reason it has to be wrapped in parentheses in this case is that if the keywordfunctionis the very first thing in a statement, then the statement is assumed to be a function statement, that is, a function declaration. (Actually, it doesn’t necessarily have to be wrapped in parentheses; it also works to prefix it with a+, or in general to put any sort of token beforefunctionthat prevents the function-statement interpretation.)The
()part after the function expression is the same as the normal()for calling a function. This:is (aside from the temporary variable) the same as this:
which is equivalent to this: