Recently I was asked by my someone to include all my code into a self containing function.I understand that closure serves the purpose of access specifiers(private, public) which are not there in Javascript but an absolute guideline about when to use and when it's not necessary to use would be really helpful.
Asked
Active
Viewed 80 times
-1
-
1Did you ask your manager for his reasoning? Probably the most common reason is to keep all of your variables out of the global scope. – James Montagne Oct 29 '13 at 19:15
-
1With some more detail this might be a good question for [Programmers.SE](http://programmers.stackexchange.com) – Oct 29 '13 at 22:51
-
@LegoStormtroopr I agree with you.But I wanted to have industry level expertise on this design issue.Thanks – Swaraj Chhatre Oct 30 '13 at 14:15
1 Answers
1
Consider two self-executing closures. What happens when they both decide to use the same variable name without realizing it? Nothing bad, because the variables are contained within closures.
(function() {
var x = 5;
function button1Click() { /* uses x */ }
}());
// ... elsewhere in the code
(function() {
var x = 10;
function button2Click() { /* uses x */ }
}());
If these two pieces of code were not contained within closures the 'x' value 5 would be overwritten with 10 and button1Click would break.
Using closures is a precautionary best-practice to avoid problems with name-space collisions where two different pieces of code use the same name without realizing it.
You should always use them unless you have a specific reason not to. Such as if two pieces of code need to access the same value - but then you need to think very, very carefully before you use global variables.

Mike Edwards
- 3,742
- 17
- 23