1

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;
}
1
  • I don't know if it's a typo or it's an actual error in your code, but you are assigning i = o (the letter "o", not a zero.) Commented Mar 18, 2011 at 5:37

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.