Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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="--";
}
like image 894
Yim Avatar asked Dec 21 '22 00:12

Yim


1 Answers

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.

like image 198
kemiller2002 Avatar answered Feb 15 '23 00:02

kemiller2002