The only reason I can think of is if you want hoisting for some reason. For example, if you want to call functions before they are declared. Personally, I don't like that style, but some people do.
I find function lexical scope more natural for JavaScript which is very function orientated, where you pass functions around and use closures a lot. I also find it a PITA having to declare variables before the block, instead of where they are first used. Ex:
if(..) {
... huge block of code ..
var foo = 1;
} Means I do not have to scroll back and forth to declare and set the variables at different places.
That's probably because you're a more experienced Javascript developer and happen to know about it - and have experienced the pitfalls already. Most people, including myself (and I'm a fairly experienced JS developer myself) find block scoping to make more sense. Less prone to bugs and whatnot too.
In strict mode JS runtimes will hoist the `var` declaration to the top of the declared scope anyway. So `foo` would be declared at the start of the containing function scope, regardless of where you appear to declare them.
Comments (110) 18 threads
Show all comments
Showing thread 14 of 18
When switching to let/const, bear in mind the difference in scope:
let/const are block-scoped:var is function-scoped:
Continue this thread — 3 replies
if(..) { ... huge block of code .. var foo = 1; }
Means I do not have to scroll back and forth to declare and set the variables at different places.
Continue this thread — 2 replies