let
-declared variables only have scope between the innermost {}
containing them; var
-declared ones are scoped to the entire function—even before the var
statement is reached.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
var
is a lot sloppier than let
. Variables can be declared with var
multiple times within the same scope, but only once with let
(and if you use let
you have to declare before you can use). So you can have
var foo;
function blablabla()
{
...
... lots of code
... some of which
... uses the global foo
... variable,
... nested control structures,
... including, buried three if()s deep,
... the line
var foo = "something";
... And suddenly that foo isn't global
... anymore and was a local
... variable all along.
}
Of course, if you wrote functions like that, then mistaking local variables for global ones is the least of your problems, but still...