Search code examples
javascriptsyntaxecmascript-6let

Why is assigning a value to the variable "let" possible?


I am taking an online JS course and the instructor used the syntax : let = names = ["Bob","Tim","Larry"]. I am convinced that was an accident, but somehow allowed by the JS environment he was using. What he ended up doing (probably by accident) was assign the array to the "names" variable, which assigned it to the "let" variable.

My question: why is this not an error? Why can "let" be used as an variable? We know "let" is a keyword. Or is it just something they haven't outlawed yet? You can still do it in the Chrome and Firefox console... and in Node, too, for that matter.


Solution

  • In ES3 and earlier JavaScript versions, let didn't have any special meaning and could be used as an identifier. const, however, was already on the list of future reserved words. See http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf, 7.5.1 Reserved Words.

    ES5 added "strict mode". const is still on the list of future reserved words and let is to be treated like a future reserved word in strict mode: http://www.ecma-international.org/ecma-262/5.1/index.html#sec-7.6.1

    ES6 gave a meaning to const and let, but let is still not a reserved word. Instead it says in http://www.ecma-international.org/ecma-262/6.0/#sec-keywords:

    In strict mode code, let and static are treated as reserved keywords through static semantic restrictions (see 12.1.1, 13.3.1.1, 13.7.5.1, and 14.5.1) rather than the lexical grammar.

    In other words, outside of strict mode, you can use let both as a variable name and to declare other variables.

    The reason let wasn't made into a reserved word is probably to not break existing code that may have used let as a normal identifier.