Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why "let = 13" don't throw an error in JavaScript? (Chrome console + nodejs)

"var, let, const" are keywords in JS, you can not name your variables with keywords.
but if you try to declare a variable named "let", it will work and throw no error.

e.g.

const = 13; //Uncaught SyntaxError: Unexpected token '='
var = 13; //Uncaught SyntaxError: Unexpected token '='
const let = 123; //Uncaught SyntaxError: let is disallowed as a lexically bound name
let let = 13; //Uncaught SyntaxError: let is disallowed as a lexically bound name
x = 13; //works good, so far so good

let = 13; //works fine,
++let // returns 14

at first, I thought because "let" is a new keyword (ES2015) so it’s backward compatibility or something like that, but you can’t do it with the const keyword or any JS keyword

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

anyone knows why?

>Solution :

It’s due to backwards compatibility, as you guessed. const has always been a reserved word (called a FutureReservedWord in the ES5 spec). You’ve never been able to name a variable const, since the beginning of JavaScript.

let had also been considered to be a FutureReservedWord, but only in strict mode – but strict mode was only introduced with ES5, when ES6 was on the distant horizon.

'use strict';
let = 10; // errors

var has always existed, so naming a variable var has always been forbidden.

Variables have never been able to be named const, but there was no such restriction with let. If it had been made forbidden in (non-strict) ES5 or ES6, it would have broken backwards compatibility, which web standards strive not to break at all costs.

If, back when JS was first engineered, people had the foresight to think: "Maybe, in the future, we’ll want to use the words const and let to declare variables, so we’ll make them reserved keywords for now." Then you wouldn’t see the inconsistency, because both would have been reserved from the beginning.

There are a number of similar keywords that sometimes have a special meaning in modern JS, but don’t throw errors when used as variable names.

static = 5;
async = 10;
await = 15;
yield = 20;
console.log('finished without errors');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading