Tchbell Tchbell - 2 months ago 6
Javascript Question

function to pick the largest number

I am trying to make a function that picks up the largest number in an array, but I can't seem to get it to go past the first number.

function largestNumber(numbers) {
var constant = 1;
for(i = 0; i < numbers.length; i++) {
if(numbers[i] > constant) {
constant = numbers[i];
}
return constant;
}
}
var numbers = [3, 4, 2, 6, 45, 775, 83, 5, 7];

largestNumber(numbers);

Answer
function largestNumber(numbers) {
    var constant = 1;
    for (i = 0; i < numbers.length; i++) {
        if (numbers[i] > constant) {
            constant = numbers[i];
        }
    }
    return constant;    // after iterating the entire array!
}
var numbers = [3, 4, 2, 6, 45, 775, 83, 5, 7];
console.log(largestNumber(numbers))
Comments