Yim
Yim

Reputation: 113

Correct way of initializing vars on this cases?

I am aware that most common practice would be to put var a,b; on the top, but I want to extract every possible character (after running on JS Uglify), and it seems they don't delete unnecessary var initializing

I want to know if any of the following will cause problems and which is recommended

Case 1:

if(condition){
    var a=-1;
    var b="++";
}else{
    var a=1;
    var b="--";
}

Case 2:

if(condition){
    var a=-1;
    var b="++";
}else{
    a=1;
    b="--";
}

Case 3:

if(condition){
    a=-1;
    b="++";
}else{
    var a=1;
    var b="--";
}

Upvotes: 4

Views: 111

Answers (2)

kemiller2002
kemiller2002

Reputation: 115488

This is the way it should be:

var a,b;

if(condition)
{
   a = -1;
   b = "++";
}
else
{
  a = 1;
  b = "--"
}

Variables should always be declared at the top of the function with the var keyword. Variable scope is at the function level, and not using var makes it a global variable. Declaring it at the top always ensures that you know the scope is for the entire function (and it is anyway), so when another programmer looks at it and doesn't know that scope is at the function level, he/she wont get confused and think the scope is only in the conditional.

Upvotes: 7

AKX
AKX

Reputation: 168966

It doesn't matter, since JavaScript has function scope, not lexical scope.

You can think of it as every var ...; statement being shunted up to the top of the function they're in. (That's what I do, at least.)

I'd write the code as

var a, b;
if(condition) {
    a = -1;
    b = "++";
} else {
    a = 1;
    b = "--";
}

Upvotes: 4

Related Questions