问题
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.
回答1:
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,
letandstaticare 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.
回答2:
It is not on the list of preserved keywords as of the version of EcmaScript your browser is implementing, due to backwards compatibility concerns. You can opt out of this behaviour by using the 'use strict' inside your .js document in modern browsers. As for a list of what keywords are to be reserved in the future but are most likely to still not be reserved in today's browsers, take a look at this list: JavaScript List of Reserved Keywords. Notice that the ones marked with * are ES5 - ES6 specific keywords, which means that those are likely to be added to the actual list at a later point.
Notice that const was added at an earlier stage and thus it is a reserved keyword today and is implemented correctly.
来源:https://stackoverflow.com/questions/45521283/why-is-assigning-a-value-to-the-variable-let-possible