4

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="--";
}
Yim
  • 115
  • 6

2 Answers2

7

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.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • sorry, you probably didn't read my last edit. I want to extract every possible character after minifying – Yim Mar 30 '12 at 19:20
  • 2
    If you don't use var, it will create a global variable. It doesn't delete them, because they are necessary. – kemiller2002 Mar 30 '12 at 19:21
  • just one last thing, why is that if I add `var hi=1;` on both the `if/else` I can access it outside the `if/else`? – Yim Mar 30 '12 at 19:31
  • Because even though you are declaring it inside the if else, the JavaScript interpreter is placing your variable declaration at the top of the function. No matter where you place it in the function it's always available throughout the entire function. – kemiller2002 Mar 30 '12 at 19:47
  • well that makes your previous comment "It doesn't delete them, because they are necessary" wrong, or we are talking about two different "them"s? (my them=unnecessary var) – Yim Mar 30 '12 at 20:00
4

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 = "--";
}
AKX
  • 152,115
  • 15
  • 115
  • 172
  • it seems the link from Wiseguy proved this true http://stackoverflow.com/questions/6964895/javascript-variable-scope-in-the-if-statement – Yim Mar 30 '12 at 19:45
  • I changed the accepted ans because yours actually says `whether if it matters or not`, while the previous accepted ans only said `what is recommended` (I really don't care best practices on minified versions) and `what caused globals` (off-topic since my examples are not the case) – Yim Mar 30 '12 at 19:51