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?

inf3rno
  • 24,976
  • 11
  • 115
  • 197
  • 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. – ibrahim mahrir Apr 25 '17 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). – RobG Apr 25 '17 at 23:14
  • You can read here, why you should use let and const, it is about "Variable hoisting" http://stackoverflow.com/questions/3725546/variable-hoisting – Slawa Eremin Apr 25 '17 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. – inf3rno Apr 25 '17 at 23:56
  • @SlawaEremkin After 20 years with js don't you think I already know variable hoisting? :D – inf3rno Apr 25 '17 at 23:57
  • 1
    @ibrahimmahrir I can accept that as a reason. So it is easier to learn js for newcomers from other languages. – inf3rno Apr 25 '17 at 23:58
  • @inf3rno Yeah exactly.! I just had discussion about it a few days ago, someone was just comming from C++ backgrounds shocked that he could use a variable declared inside a `for` loop outside its block of instructions. – ibrahim mahrir Apr 26 '17 at 00:14

1 Answers1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Const are great, but let can lead to some interesting errors... for example asking `typeof` block variable before initializing lead to error... – Akxe Apr 25 '17 at 23:11
  • 4
    @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. – Felix Kling Apr 25 '17 at 23:17
  • Thanks! I'll keep `var` and I'll might practice `let` and `const` by my hobby projects. – inf3rno Apr 26 '17 at 00:02
  • @Akxe—I think that's covered by "*`let` has a temporal dead zone*". – RobG Apr 26 '17 at 00:15
  • Problem is, that `var` will return `undefined`, while `let` will crash your program – Akxe Apr 26 '17 at 10:01
  • @Akxe Yes, `var` yielding `undefined` when you've made a mistake instead of crashing the program is a problem. – Bergi Apr 26 '17 at 12:32