Skip to content Skip to sidebar Skip to footer

Is There Anything Wrong With Declaring Your Vars Inside Of A For Loop Or An If Block?

I often see the habit: var foo, bar; for(var i = 0; i < 5; i++) { foo = '' + foo + i; } It's also rubbed off onto me, but I've just realized I have no idea why I do it.

Solution 1:

There is no real problem with doing it, however javascript does not have block level scope, so if you declare foo inside the loop it's still accessible throughout the whole function.

There is a small advantage when doing minification if you declare all your variables up front, consider:

// Up frontvar a, b, c, aVal, bVal, cVal;

for (a = 0; a < 5; ++a) {
    aVal = a;
}

for (b = 0; b < 5; ++b) {
    bVal = b;
}

for (c = 0; c < 5; ++c) {
    cVal = c;
}

// Inlinefor (var a = 0; a < 5; ++a) {
    var aVal = a;
}

for (var b = 0; b < 5; ++b) {
    var bVal = b;
}

for (var c = 0; c < 5; ++c) {
    var cVal = c;
}

In this case, when you minify there will be a lot more "var" statements appearing in your source. It's not a huge deal, but they can certainly add up over time.

Post a Comment for "Is There Anything Wrong With Declaring Your Vars Inside Of A For Loop Or An If Block?"