Reputation: 43
Type conversion to string in javaScript apparently ignores let as a keyword.
String(let)
throws the error ReferenceError: let is not defined
Whereas, String(var)
throws the error SyntaxError: Unexpected token 'var'
Is that the intended behaviour?
Upvotes: 2
Views: 313
Reputation: 370679
"Reserved keywords" cannot be used as identifiers (variable names). var
is a reserved keyword.
let
is not a reserved keyword, because that would break backwards compatibility: ancient scripts written without ES6 in mind that happened to use let
as a variable name would fail (and browsers try very hard not to break backwards compatibility
So using String(var)
throws a syntax error, but syntactically permits the use of let
- up until the point where you try to reference it (at which point an error is thrown because no such variable named let
exists).
For the exact same reason, it's possible to define a variable named let
, but not to define a variable named var
:
var let = 123;
console.log(String(let));
var var = 123;
console.log(String(var));
Also, let
can't be declared as an identifier in strict mode:
'use strict';
var let = 123;
console.log(String(let));
This is possible because if strict mode is being used, the code that is running is guaranteed to have been written after ES5 (and so there isn't any backwards compatibility to worry about).
As a comment notes, this is not string interpolation. This is just the parser identifying valid variable/identifier names.
Upvotes: 3