I’ve been told that javascript variables should all come before they are used in a function, such that:
function contrived() {
var myA, myB;
myA = 10;
myB = 20;
return myA + myB;
}
Is prefered over:
function furtherContrivance() {
var myA = 10;
var myB = 20;
return myA + myB;
}
Is this the case? And why is that?
I guess some people might prefer the former style because that’s how it works inside. All local variables exist for the entire lifetime of the function, even if you use
varto declare them in the middle of the function.There’s nothing wrong with declaring variables later in the function, syntax-wise, it might just be confusing as the variables will then exist before the line that declares them. Hence this function:
Is equivalent to this:
Another related fact is that nested function definitions (done using
function foo() { ... }) will get moved to the top of the containing function as well, so they will be available even if the code that calls them comes before them.