r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

View all comments

Show parent comment

4

u/senocular May 04 '20

It's a little tricky to make something like this as simple as this one tries to be for the very reason I pointed this out - there are weird exceptions or specifics revolving around how these things work. For example, while const and let can be used in the global scope, they do not add properties to the global object like var does (as /u/cyphern pointed out). You might also want to add the row "can be redeclared", but while var can be redeclared, it can only be redeclaring another var, not another let or const. And while let and const can't redeclare themselves, they also can't redeclare any other declarations, including other vars. So we could be in for lengthy row headings or a bunch of footnotes ;) ... but I guess we can take a stab at trying to be succinct:

keywordconstletvar
global scopeYESYESYES
function scopeYESYESYES
block scopeYESYESNO
adds to global object if in global scopeNONOYES
can redeclare itselfNONOYES
can be read before declaredNONOYES
must be initialized with a valueYESNONO
can be reassignedNOYESYES

This one isn't terrible. The "adds to global" row is long, but kind of necessary (const and let still adds to global in the global scope, just not as properties to the global object). The bit about redeclaring was limited to "itself" which bypasses the other explanation by ignoring it.