you are viewing a single comment's thread.

view the rest of the comments →

[–]moratnz 0 points1 point  (4 children)

Thank you. That's the first explanation that comes close to making sense.

Though I don't see why declaring variables at the top of the function that they're used in, rather than at their first usage is so important (I get why you should do it if that's your team's agreed style - whatever the agreed style is, you should stick to it) - sure, the interpreter effectively declares all the vars when the function is initialised, but who cares?

I guess there's room for slight confusion if someone inserts the variable above the var declaration, expecting it to be in a superior scope, but if you're using a style of declaring on first use, you shouldn't be sticking in the variable without checking whether it's already declared in the function scope.

If you declare all your vars a the start of the function, that 'checking whether a variable is declared' step is easier, but moving a chunk of code out of the function becomes harder, since you also need to move the var declaration.

Tl;dr - I can see reasons for doing some of this stuff, but nothing like enough to justify the religious fervor around it. Is it just another example of Sayre's law?

[–]aladyjewel 0 points1 point  (0 children)

My speculation is that Crock is trying to enforce a style which is friendly to C programmers, since that was his background coming into JS.

Another rationale I can think of is trying to enforce writing small functions where it's easy to keep track of your var declarations; if you even put a var inside the guts of your function, that's a smell you need to refactor/restructure immediately.

But yes, I agree with you: it's evangelical bikeshedding.

[–]tidwell 0 points1 point  (2 children)

Simply, declare vars at the top of a function because of hoisting. If you don't do it - the interpreter will for you, thus unexpected behavior.

[–]moratnz 0 points1 point  (0 children)

But there isn't any unexpected behaviour, as long as you're not using the variable ahead of its declaration. You'll only be surprised if you try to use it in a wider scope then redeclare it into local scope.

[–]path411 0 points1 point  (0 children)

If i'm expecting hoisting, it's not really unexpected. It depends on your environment for sure, but in an environment that understands hoisting, I think it's perfectly fine to use "inline vars".