5

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;
  } 
}
2

1 Answer 1

5

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).

2
  • I'm curious: you said "to support older browsers that aren't compliant yet, you can use [...] a scoping function", and then you put a let in the function... since the old browser is not compliant, wouldn't that throw an error? Commented Aug 12, 2017 at 10:15
  • 1
    @Geraldo: Thanks for flagging that up. Depends how old. IE9+ support let, but not with the correct ES2015 semantics; so you'd have to go back to IE8 for that to fail. But I really should have changed it to var (and so now I have). Commented Aug 12, 2017 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.