Javascript- How to write a function that finds the max number in any set of numerical arguments

Viewed 833

I am completing an exercise on JavaScript Hero (https://www.jshero.net/en/success.html) and I was able to get the function to work, however, I'm hoping someone could tell me WHY it works. I'd really appreciate it.

The challenge is... "Write a function max that calculates the maximum of an arbitrary number of numbers. Example: max(1, 2) should return 2 and max(2, 3, 1) should return 3."

My answer is...

function max (){

    let ans=0;

    for (let i = 0; i < arguments.length; i++) {
        if (arguments[i] > ans){
            ans= arguments[i];
        }
    }
    return ans;
}

What I don't understand is setting ans to zero and then saying if arguments[i] is greater than zero then that is the answer. Wouldn't theoretically the first argument over zero be returned as the answer? Also, what if your passed in arguments are negative numbers, (-1,-5,-15) for example? Would the function not work then?

I would really appreciate any input on this. Even though I got the right answer, I want to understand what is going on in the code. Thanks! :)

4 Answers

You could take the first paramter as local max value and iterate from the second parameter.

function max() {
    let ans = arguments[0];

    for (let i = 1; i < arguments.length; i++) {
        if (arguments[i] > ans) {
            ans = arguments[i];
        }
    }
    return ans;
}

console.log(max());
console.log(max(3, 2, 1));

Looks like ans is only 0 initially. The value of ans changes on each comparison.

So, say you pass the array [1,2,5,4] to the max function, this is how it will go down:

  • Is 1 bigger than 0? Yes, so ans becomes 1.
  • Is 2 bigger than 1? Yes, so ans becomes 2.
  • Is 5 bigger than 2? Yes, so ans becomes 5.
  • Is 4 bigger than 5? No, so ans stays 5 and is returned to the user as the largest number.

The logic is to compare two numbers at a time to determine which number is greater. The code that you provided would only work if all the numbers in the argument are positive integers.

function max_val(arr){
    
    for (let i=0;i<arr.length;i++){
        
        for (let j=0;j<arr.length;j++){

           if (arr[i]>arr[j]){
             arr[j]=arr[i];
           }
        }
    }
    console.log(arr[1]); 
}
Related