0

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?

2

1 Answer 1

5

Usually in these types of questions, I refer the ESLint for guidance as they explain very plainly why the rules are as they are, take a look at no-var rule.

The main reason is for readability. the behaviour you are referring to is hard to read and track and here is an example .

Also, the second snippet of code is by far easier to track and debug, and defining the variable in the correct scope (first example the var is used outside the scope of definition, which is misleading and can cause problems like shadowing ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.