I was really glad that ES6 introduced the let
keyword for defining variables. var
scoping rules can lead to all kinds of issues, especially when working with loops and event handlers. Even when programmers used var
in the past, they still almost always expected let
scoping rules.
Variables declared with var
are available in the entire function. Variables defined with let
are only available inside the block where they are declared.
However, var
's scoping rules are also useful sometimes, though very rarely. Here is an example: (imagine all of these examples are inside a function, I don't intend to define globals here)
try {
var result = mightThrowAnException();
//do various things
}
finally {
if (result) cleanup(result);
}
//do other things
callSomeFunction(result); //reference result
return result;
In the above example, replacing var
with let
would cause an error. In order to use let
, one would have to write a function like this:
let result; //declare the variable outside the braces
try {
result = mightThrowAnException();
//do various things
}
finally {
if (result) cleanup(result);
}
//do other things
callSomeFunction(result); //reference result
return result;
I honestly think writing it this way isn't any better. It feels worse when you have to predefine more variables like these, just because they're declared in a try
block.
In TypeScript, there is the additional annoyance that you have to explicitly declare the type of result
if you want to predefine it in this way. If you initialize it, the type will be deduced automatically.
Is it a good idea to use var
instead of let
to take advantage of these scoping rules, when in almost every other part of your code you use let
?
var
variation to work, so it violates the principle of least surprise.