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?
-
1Because 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– ibrahim mahrir2017-04-25 23:10:46 +00:00Commented Apr 25, 2017 at 23:10
-
2You 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– RobG2017-04-25 23:14:16 +00:00Commented 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-hoistingSlawa Eremin– Slawa Eremin2017-04-25 23:15:24 +00:00Commented 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.inf3rno– inf3rno2017-04-25 23:56:46 +00:00Commented 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.inf3rno– inf3rno2017-04-25 23:58:34 +00:00Commented Apr 25, 2017 at 23:58
|
Show 2 more comments
1 Answer
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.
6 Comments
Akxe
Const are great, but let can lead to some interesting errors... for example asking
typeof block variable before initializing lead to error...Felix Kling
@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.inf3rno
Thanks! I'll keep
var and I'll might practice let and const by my hobby projects.RobG
@Akxe—I think that's covered by "
let has a temporal dead zone".Akxe
Problem is, that
var will return undefined, while let will crash your program |