Why enclose javascript file in a function?

Variables in Javascript have function scope. You're wrapping your code in a function in order for it not to clobber the global namespace with tons of variables, which may lead to bugs later on when different code is added. E.g.:

// module 1
(function () {
    var foo = 'bar';
    ...
})();

// module 2
(function () {
    var foo = 'baz';
    ...
})();

No problems, because both modules have their own variable scopes.


Maybe its better to refer you to some good resources

related topic in stackoverflow

What are the benefits of a closure, and when are they typically used?

some detail explaination

http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

or more:

search result from stackoverflow

https://stackoverflow.com/search?q=javascript+closure

Tags:

Javascript