NOTICE . It really is too long, but I hope someone finds it useful.
To begin with: $ (or jQuery , they are usually the same thing) is a function. In the first two examples, you call this function, passing it a link to an anonymous function. This is a jQuery shortcut for adding a function to be passed as the event listener "document.ready" (the actual name of the DOMContentLoaded event in compatible browsers).
JavaScript has three ways to create functions:
1. Function declaration
function foo() {
In a declaration, a function should always be named. In this case, the function name is "foo".
2. Function expression
Can be called or not. They are usually anonymous. They will be considered invalid syntax depending on the position that they appear in the code. For example, this is a syntax error:
But this is not so:
This is also true:
It is too:
The two previous examples are commonly used to call a function immediately:
!function() { alert('invoked') }(); (function() { alert('invoked') }());
Isolated, without calling parentheses, they are almost useless, since links to a newly created function are immediately lost if we do not assign it to anything.
This, on the other hand, is very useful:
3. Using the Function constructor
You also said that you are confused by functions and variables that do not exist in a particular context. This is because of scale: in JavaScript, every function creates a new scope. If you create a variable (declared using var ) or another function (using any of the valid options above), this variable or function will not be visible outside the function in which it was declared. But they will be visible inside other nested functions defined in the same area (nested functions are “closed”, they are an external area and therefore are usually called “closures”).