Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is let=0 valid but not var=0? [duplicate]

Tags:

javascript

Why doesn't

let=0

show any syntax errors but

var=0

does? (I test it on Safari)

However I tried

console.log(let)

but it has errors and seems 'let' is not a already defined variable. Why would that happen?

like image 816
ocomfd Avatar asked Feb 26 '18 09:02

ocomfd


Video Answer


1 Answers

Because var has been a keyword forever, but let has not. So when adding let to the language, the TC39 committee had to specify it such that existing code that used let as an identifier didn't break. (One of their prime rules is "don't break the web" and they take it very seriously [thankfully].)

So let is a keyword in context, such as a let declaration, but can also be an identifier:

let a = 42;                // Keyword, due to context  let = "I'm an identifier"; // Identifier, due to context   console.log(a);  console.log(let);

Note that in strict mode ("use strict"), let cannot be used as an identifier; the spec that introduced strict mode also reserved let and a few other words when used in strict mode (see ECMAScript 5th edition §7.6.1.2), since of course no strict-mode code existed in the wild prior to that spec's adoption, so they could do that. (It didn't reserve every single word that's ended up being a keyword since, so sometimes they really have to define things very carefully indeed. For instance, async is a perfectly valid identifier even in strict mode, but has special meaning just before function.)

"use strict";  let = "I'm an identifier"; // SyntaxError: Unexpected strict mode reserved word  console.log(let);
like image 81
T.J. Crowder Avatar answered Oct 21 '22 04:10

T.J. Crowder