Why is a JavaScript reserved keyword allowed as a variable name? [duplicate]

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?

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;

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, and public;

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

Read More:   ReferenceError : window is not defined at object. Node.js

"use strict";
var let = 3

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts