Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why enclose javascript file in a function?

Tags:

I've been playing around with Node.js after having not used JavaScript for a long time.

One thing I've noticed is that many of the sample files I've been looking at use the following convention:

(function() {
... all javascript code for the file ...
})();

Is there a reason to enclose all the JavaScript in a file in a function like that, or is it just convention? Is it something I should mimic?

I should also note, that at least in the files I've been playing with, the code works the same way with or without the function surrounding everything.

Thanks for your insights!

like image 873
paul Avatar asked Jun 29 '11 05:06

paul


People also ask

Why do we need JavaScript closures?

In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.

Why wrap the content of a JS source file in a function block?

The purpose of wrapping is to a namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries.

What is the function of JavaScript file?

Manipulation of file handling in JavaScript involves opening of file, closing of file, Updating data in file. JavaScript file handling does not get compiled by any compiler. It just needs an environment with a working browser where the translator can handle the java script code for the web browser.

Why are closures useful?

Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.


1 Answers

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.

like image 144
deceze Avatar answered Oct 06 '22 00:10

deceze