Using let variable instead of using global variables

I heard that using a global variable in JavaScript is bad. Since let is a block area, can I use it inside a block that includes all other functions and use it like global variables?

 { var b = 10; let c = 20; function foo(){ return c; } } 
+5
source share
1 answer

Yes, you can, with reservations (see below). In your example, b is global, but c not.

Note that foo in this code is global in free mode, so if you intend to do this, use "use strict"; at the top of your code.

Also note that not all browsers correctly support ES2015 semantics for let , function declarations in blocks, etc.

To support older browsers that are not yet compatible, you can use the older method: Scope detection function:

 (function() { var b = 10; var c = 20; function foo(){ return c; } })(); 

There b and c are local, not global, although I used var for them.

Of course, another option for supporting older browsers is to use a transpiler, such as Babel , and ensure its compatibility with ES5 code (and include the necessary policies). For really outdated browsers such as IE8 (which, unfortunately, are still preserved to some extent), you may need to output ES3 code (and you will need more poly regiments).

(Strict mode is still handy for other things, even with the scope function, for example, using the Horror of Implicit Globals [disclosure: this is a post on my anemic little blog].)

In both cases, in the scope or function of determining the scope, you get variables that are global with respect to your code (inside a block / function), but are not really global and therefore do not have some problems that have global global variables, for example, conflict with built-in functions unexpectedly (for example, name in the global scope of browsers, which is always a string, even if you assign it a number or function - because it is window.name , the name of the window).

+5
source

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


All Articles