I've heard that using global variable is bad in JavaScript. Since let
is block-scoped can I use it within a block that includes all other functions and use it in a similar way to global variables?
{
var b = 10;
let c = 20;
function foo(){
return c;
}
}
Yes, you can, with caveats (see below). In your example, b
is a global, but c
is not.
Note that foo
in that code is a global in loose mode, so if you're going to do that, use "use strict";
at the top of your code.
Also note that not all browsers correctly support the ES2015 semantics for let
, function declarations in blocks, etc.
To support older browsers that aren't compliant yet, you can use the older way: A scoping function:
(function() {
var b = 10;
var c = 20;
function foo(){
return c;
}
})();
There, b
and c
are both local, not global, even though I used var
for them.
Of course, another option for supporting older browsers is to use a transpiler, like Babel, and have it produce ES5-compatible code (and include the necessary polyfills). For truly obsolete browsers like IE8 (which still sadly survives to some degree), you may need it to output ES3 code (and you'll need more polyfills).
(Strict mode is still handy for other things even with a scoping function, such as doing away with The Horror of Implicit Globals [disclosure: that's a post on my anemic little blog].)
In both cases, a scoping block or a scoping function, you end up with variables that are effectively global to your code (inside the scoping block/function), but aren't really globals and so don't have some of the issues true globals have, such as conflicting with built-ins in unexpected ways (such as name
at global scope in browsers, which is always a string even if you assign a number or function to it — because it's window.name
, the name of the window).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With