String(let) throws the error ReferenceError: let is not defined
String(var) throws the error SyntaxError: Unexpected token ‘var’
Is that the intended behaviour?
“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
- see that question for an extended explanation).
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
For the exact same reason, it’s possible to define a variable named
let, but not to define a variable named
var let = 123; console.log(String(let));
var var = 123; console.log(String(var));
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.