super11
super11

Reputation: 476

Why is this for loop not working?

What is the exactly difference between:

<p id="test"></p>

<script>

function findMax() {
    var i;
    var max = -Infinity;
    for(i=0;i<arguments.length;i++) {
        if(arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
}

document.getElementById('test').innerHTML = findMax(32, 133, 83, 163);

</script>

and:

<p id="test"></p>

<script>

function findMax() {
    var i = 0;
    var max = -Infinity;
    for(; i < arguments.length ; i++) {
        if(arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
}

document.getElementById('test').innerHTML = findMax(32, 133, 83, 163);

</script>

Maybe I have missed some classes but the first one outputs 163, as it should, while the second one outputs 0. The console says

SyntaxError: return not in function

return max;

Why does the second one return the lowest value, while the first one returns highest value?

Upvotes: 0

Views: 71

Answers (3)

gurvinder372
gurvinder372

Reputation: 68393

while the second one outputs 0.

You didn't initialize i to 0.

Which means i was undefined, and undefined + 1 is NaN.

SyntaxError: return not in function

You missed a curly brace after for-loop, so the return statement went outside the function definition

function findMax() {
    var i;
    var max = -Infinity;
    for(i = 0; i < arguments.length ; i++)
    {//this was missed
        if(arguments[i] > max) 
        {
            max = arguments[i];
        }
    }
    return max;
}

Upvotes: 3

apomene
apomene

Reputation: 14389

in second you are missing a {, try:

function findMax() {
    var i;
    var max = -Infinity;
    for(; i < arguments.length ; i++) {
        if(arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
}

Upvotes: 1

Yukul&#233;l&#233;
Yukul&#233;l&#233;

Reputation: 17062

for the 2nd one you forget the opening bracket { and initial value i=0

You can also simply use Math.max()

Upvotes: 1

Related Questions