let in Javascript
I’ve noticed in the past that Mozilla and Gnome code was religious about using
let instead of var, but I’d never really looked into it. I am often
skeptical about such absolutist style declarations, having been burned by a
few, but it generally seems like a good idea.
Javascript has two other ways of declaring variables, one implicit
foo = 'bar'
one explicit
var foo = 'bar'
The implicit declaration is clearly the easiest, requiring no ceremony or
planning. Unfortunately, this means the variable is global. That’s right,
completely, totally global with no insulation from anything else. The second,
var, is function-scoped. That seems reasonable, but it leaves out constructs
that create their own scope in every other civilized language- like for
loops. for loop index variables leaking out is a classic Javascript beginner
trap. let fixes this, and has the block-scoped semantics you might expect.
Honestly, it’s a little more block scoped than most- if blocks count as blocks,
unlike, say, Python, where this works-
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> if True:
... y = 22
...
>>> y
22
let is not special cased in Javascript-
gjs> y
ReferenceError: y is not defined
gjs> if ( true ) { let y = 22; }
gjs> y
ReferenceError: y is not defined
gjs>