Skip to content Skip to sidebar Skip to footer

Javascript: Why Do I Need To Declare Var I = 0 In The For Loop?

I was doing a problem that required recursion, for counting coin combinations that add up to a certain amount. The solution that works is below. One thing that bothered me for hour

Solution 1:

Yes.

Your assumption is correct. If var is omitted, the variable will be global (or throw an error, depending on your browser).

If your function is recursive, there will obviously be interference when the loops from different places in the stack are changing (and relying on, for iteration) the same variable.

Solution 2:

Its scoped to the function not the for-loop block. some people put it outside. It has the same effect both ways.

var i = 0;
for (; i<foo.length; i++) {
}

You should always use var when declaring variables in es5. It is worth reading up on how it is scoped (hint: usually to the function its declared in). In es6 we have let which is scoped to the block its declared in (in this case the for-loop)

Solution 3:

Because in javascript you have to explicit declare your variable before you want to use it. So if you write

for(i=0;...;i++)

where is the variable i come from? Javascript will throw error: Uncaught ReferenceError: i is not defined

Solution 4:

Yeah of-course it won't work, i is variable and it has to be initialized.

And yes you can declare it outside for loop. But i think you had declared it outside the function which will not work.

functioncombo(index,amount) {
var i;
for (i = 0; i <= Math.ceil(amount / coins[index]); i++) {
    amountleft = amount - (i * coins[index]);
    if (amount < 0) {
        break;
    }
    if (amountleft == 0) {
        ways ++;
        break;
    }
    if (amountleft > 0) {
        combo(index + 1,amountleft);
    }
}
}   

Post a Comment for "Javascript: Why Do I Need To Declare Var I = 0 In The For Loop?"