Why is a JavaScript reserved keyword allowed as a variable name?

Md. Tahazzot :

We know that let is a reserved keyword that defines a variable in JavaScript.

var let = 2;
console.log(let); // return 2

So why is this not an error?

CertainPerformance :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21738&siteId=1