in the last few days i’m interesting in anonymous function in javascript , so i started to “explore” frameworks such as jquery , in the very first line i saw this piece of code :
var jQuery = (function() { .. functions .. }();
and a question came in mind – what is the purpose of that code?
why a variable contain anonymous function? what is the uses with that var? is it kind of function container or something? if it is how to access the functions?
You are actually missing a closing parenthesis for this code to be valid javascript:
It defines an anonymous function and executes it immediately storing the result of it in the variable.
You can think of it like this:
It’s just that they didn’t bother to define
fooas an external function as they didn’t need to call it elsewhere in the code. So they defined it as an anonymous function.By doing this everything that is declared inside this anonymous function is scoped and accessible only to the containing anonymous function. It is not accessible to the outside.