There's a popular JavaScript question What's the difference between using “let” and “var” to declare a variable?. The question has been viewed 286k times and has a score of 1468, and the top answer has a score of 2256.
The top answer contains some misinformation. It says about var
and let
:
Both are global if not in a block.
And also:
Global:
They are identical when used like this outside a function block.
let me = 'go'; //globally scoped var i = 'able'; //globally scoped
This is incorrect. MDN says that:
At the top level of programs and functions,
let
, unlikevar
, does not create a property on the global object. For example:var x = 'global'; let y = 'global'; console.log(this.x); // "global" console.log(this.y); // undefined
OP has been notified of that fact in comments, twice:
their is a difference in global scope:
let
don't add property to global variable 2ality.com/2015/02/es6-scoping.html#the_global_object – Yukulélé Sep 26 '15 at 10:51
let
at the top level scope is not identical tovar
--let
explicitly will not create globally-scoped references: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Dave Newton Mar 31 at 21:28
If you look at the revision history, you'll see that multiple users tried to correct that misinformation, but every time their edit was rolled back by the OP.
Also, that answer is incomplete—it doesn't mention TDZ at all or the fact that the same variable can't be declared twice using let
.
What should we do about that? I think it's vitally important to correct that, unless we want to become the second W3Schools.
Possible solutions that IMO won't work:
- Force the OP to edit their answer. I don't think it's a good idea, because it's their answer, and they are free to tell whatever they want in their answer.
- Add a new, correct answer. This won't work, because the question already has many answers, and that new answer would stay at the bottom and wouldn't be noticed by many users.
let
has never, to my knowledge, added properties to the global object. That's just not what it's for. So to the extent that the keyword exists in a given version of JS, it does not do what the answer in question says it does. (That is, this was not a breaking change introduced by ES6; it waslet
's semantics all along.)