Why are closures better than global variables for storing variables?

I understand how closures work in JavaScript, but my question is, why would you solve all closure problems to save a variable? Could you just make the variable global? Or it clutters the global reach and makes your code error-prone.

+4
source share
6 answers

This is problem. Global variables are: global, for everyone. With the closure of the possibility (visibility) of variables, you can better control it, which means that possible unintended side effects can be better controlled.

http://en.wikipedia.org/wiki/Global_variable

[Globals] are usually considered bad practice precisely because of their non-locality: a global variable can potentially be changed from anywhere (if they are not in protected memory), and any part of the program can depend on it. Consequently, a global variable has unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. See action from a distance

+6
source

Two words: race conditions.

If you set a variable in the global scope, while its intended use is local to the function instance, you run the risk of having two (or more) unique instances that access and manipulate this global variable, and all instances behave unpredictably.

There are many other reasons why you should be extremely careful when storing a local state in global space.

One could reuse the state of the last instance that set this variable (if you do not have multiple instances at the same time).

Conflicts with other code fragments that rely on a global variable with the same name are also possible.

Aesthetically, you also turn the global namespace into a mess (there are a lot of random variables there without any direct information on why they are there in the first place).

The inclusion of variables in global space is error prone and creates a mess of runtime representations. The capabilities of the JS review also make it unnecessary, so no one does it (except for the things that are really there).

As an additional comment, do not mention your age or show off your coding skills in future issues. This does not apply to the issue.

+3
source

There is only one global namespace in JavaScript, so it would be quite difficult to use different Framework / Toolkits on the same page, because sooner or later the variable names will start to collide.

Closing also provides a way to emulate private variables:

function Counter(start) { var count = start; return { increment: function() { count++; }, get: function() { return count; // only gives you the value, but no write access } } } 

But, which is a pretty โ€œdumb" example, closures are especially useful when it comes to callbacks of all kinds, you donโ€™t want to manage global arrays that store data for each callback, itโ€™s very simple and cleaner with closures.

For extreme use of closures, take a look at the JavaScript implementation class. (Disclaimer, the code was written by me.)

Here proto keeps track of the original properties of each class, but is still available for extend , which can then add these properties to other classes when they inherit from another.

+2
source

One reason is the prevention of global pollution. Another is to use the same implementation for many operations by simply changing the passed value.

 js> makeadd = function(num) { return function(val) { return num+val } } function (num) { return function (val) {return num + val;}; } js> add3 = makeadd(3) function (val) { return num + val; } js> add4 = makeadd(4) function (val) { return num + val; } js> add3(add4(2)) 9 
+1
source

Everyone else has already mentioned the pollution of the name of the global and globally evil , even OP:

Or is it cluttering the global reach ...

but there is one more reason.

There is only one instance of a global variable. This makes it not scalable enough. If at some point in the future you need more than one instance of an object, you will need to create a second global variable or convert the original variable into an array and manage this array manually (i.e. decide for yourself when to delete the object from memory).

If it has already been created by closure, then the creation of the second, third and fourth instances can simply be done by calling a function that creates the closure again and again. You also get the added bonus that all created instances automatically collect garbage when they are no longer needed.

This situation happens more often than you think. Imagine that you just created an animation sequence, an animation of text, for example, to disappear. And you used a global variable to track the state of the animation. And you think this is great and good, and forget about it. Then after some time, your boss comes to you and says that he likes the animation, and would like to add it to other things on the page. Now you need to deal with the processing of several animations at the same time and you need to convert this global array to an array so that one animation does not knock the other current animation .. if they were encapsulated in closure to start with ...


And what do you know, just as I was scrolling after I submitted this answer, I found a question illustrating the problem with global variables: How to create multiple timers on the same page that work independently - javascript? . Although you really don't need to close for this particular problem, it's just plain old variables.

+1
source

When leaving home, itโ€™s nice to give the key to a neighbor so that your spouse can collect it if he arrives home sooner or later, but you should not throw it on the road.

+1
source

Source: https://habr.com/ru/post/1333435/


All Articles