mjmitche
mjmitche

Reputation: 2067

JavaScript setting variables?

Can someone explain the second line of this function? is it setting two variables to = 0 at one time? i.e. var i = 0 and var res = 0? If so, is it necessary to set var i = 0 considering that it does that in for(i = 0 ... etc

function sumOnSteroids () {
    var i, res = 0;
    var number_of_params = arguments.length;
    for (i = o; i < number_of_params; i++) {
        res += arguments[i];
    }
    return res;
}

Upvotes: 1

Views: 128

Answers (2)

alex
alex

Reputation: 490153

It is setting two variables at once with the var keyword being applied to both, scoping them. Without the var, they would be properties of window (essentially globals).

The first one (i) would be undefined and the second one (res) would be 0.

This is a powerful pattern because...

  • var should be implicit, but it is not, so we only have to repeat it once.
  • Less typing for you.
  • Better for minifying (smaller file size).

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30082

No, the value of i will be undefined, the initializer only applies to "res" in that case. To assign the value you'd need:

var i = 0,
    res = 0;

Upvotes: 1

Related Questions