0

Function scoping was perfectly fine for me for 2 decades. Now I read everywhere, that I should use let and const instead of var. I guess this is mostly because it's a new feature. Why should I prefer block scope?

7
  • 1
    Because JS was criticised for a long time for not respecting block scopes that all other languages (at least famous ones) did respect. Now JS is moving towards those languages by filling a lot of gaps. Commented Apr 25, 2017 at 23:10
  • 2
    You should not, unless you have a good reason to do so. One good reason to continue to use var is that it's backward compatible. const and let restrict the environment in which your code will run for very little benefit, you can get similar benefits from strict mode (which is backward compatible too). Commented Apr 25, 2017 at 23:14
  • You can read here, why you should use let and const, it is about "Variable hoisting" stackoverflow.com/questions/3725546/variable-hoisting Commented Apr 25, 2017 at 23:15
  • @RobG Thanks! I think the same, this block scope does not have any advantage. I will use it by my hobby projects, where I control the environment, otherwise ES5 will be okay. Commented Apr 25, 2017 at 23:56
  • 1
    @ibrahimmahrir I can accept that as a reason. So it is easier to learn js for newcomers from other languages. Commented Apr 25, 2017 at 23:58

1 Answer 1

6

const has the obvious advantage that it's a constant binding. let has a temporal dead zone, and its forbidden to redeclare an identifier in the same scope, so it helps to prevent certain mistakes.

Apart from those, there's nothing wrong with continuing to use var when you don't need a block scope.

Sign up to request clarification or add additional context in comments.

6 Comments

Const are great, but let can lead to some interesting errors... for example asking typeof block variable before initializing lead to error...
@Akxe: And why would you ask for the type if the variable wasn't initialized yet? I consider the errors thrown for let cases a feature.
Thanks! I'll keep var and I'll might practice let and const by my hobby projects.
@Akxe—I think that's covered by "let has a temporal dead zone".
Problem is, that var will return undefined, while let will crash your program
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.