Why is a JavaScript reserved keyword allowed as a variable name?
let
is only a reserved word in strict mode:
'use strict';
var let = 5;
Uncaught SyntaxError: Unexpected strict mode reserved word
This is because browsers generally prioritize backwards compatibility above all else. Although let
was introduced in ES2015 (and its use was forseen sometime before then), prior scripts which used let
as a variable name would continue to work as desired. For example, if your script was written in 2008:
var let = 2;
console.log(let);
Then it would continue to work in 2020 as well.
For very similar reasons, async
and await
are also permitted as variable names.
As for why the use of let
errors in strict mode - strict mode was introduced in ES5, in 2009. Back then, the language designers saw that the use of new keyword(s) to declare variables was a possibility in the future, but it wasn't set in stone yet, and ES6 was still a long ways off. Once ES5 came out, script writers could opt-in to strict mode to make code less confusing, and change silent errors to explicit errors. Although let
wasn't usable for variable declaration yet, prohibiting it as a variable name in strict mode improved the readability of future scripts which opted into strict mode, while also not breaking any existing scripts.
let
and some of the other works acts as reserved words only in strict mode. The specs says
Disallowed in strict mode: Those that are contextually disallowed as identifiers, in strict mode code:
let
,static
,implements
,interface
,package
,private
,protected
, andpublic
;
You can see let
inside the list of words which are only disallowed in strict mode. If you want to throw error for using let
as variable name you can use strict mode
"use strict";
var let = 3