//Version A:
var let = true;
console.log(let);//true
//Version B:
let let = 0; //syntax Error: let is disallowed as a lexically bound name
console.log(let);
Is there any particular reason where we allow variable with name let created using var but not let? With this experiment, is that also means that variable name let is ok to exist on global level but not in some scope level? But isn't global is consider scope?
It's due to backwards compatibility, as you guessed. const has always been a reserved word (called a FutureReservedWord in the ES5 spec). You've never been able to name a variable const, since the beginning of JavaScript.
let had also been considered to be a FutureReservedWord, but only in strict mode - but strict mode was only introduced with ES5, when ES6 was on the distant horizon.
'use strict';
let = 10; // errors
var has always existed, so naming a variable var has always been forbidden.
Variables have never been able to be named const, but there was no such restriction with let. If it had been made forbidden in (non-strict) ES5 or ES6, it would have broken backwards compatibility, which web standards strive not to break at all costs.
If, back when JS was first engineered, people had the foresight to think: "Maybe, in the future, we'll want to use the words const and let to declare variables, so we'll make them reserved keywords for now." Then you wouldn't see the inconsistency, because both would have been reserved from the beginning.
There are a number of similar keywords that sometimes have a special meaning in modern JS, but don't throw errors when used as variable names.
static = 5;
async = 10;
await = 15;
yield = 20;
console.log('finished without errors');
Because the specification says so.
From https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations-static-semantics-early-errors:
13.3.1 Let and Const Declarations
13.3.1.1 Static Semantics: Early Errors
LexicalDeclaration
:LetOrConst BindingList;
- It is a Syntax Error if the BoundNames of BindingList contains
"let".
The variable statement specification has no such limitation, probably because let was not in use at the time var was defined, and changing the specification for var would be a breaking change.
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