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! :)