Doubts about this example

HI!

I was reading some information to find the MAX and MIN number from an array, but I saw this code, and I have some doubts…I would appreciate any help provided.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>The highest number is <span id="demo"></span>.</p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    var len = arr.length;
    var max = -Infinity;
    while (len--) {
      if (arr[len] > max) {
        max = arr[len];
      }
    }
    return max;
}
</script>

</body>
</html>

why does the function say function myArrayMax(arr), I know arr is the parameter, but then, the parameter is not given but the function works perfectly in the example. Shouldn’t it be function myArrayMax(points)?

After that, why does it say that var max=-infinity?

Why is it that if the number is > than -infinity it will be the max?

Thank you for your help.

Link to the example
Link to the website

The function definition can use any parameter name it likes. They decided to use arr because this describes the parameter type but they could equally validly have called it ‘astronaut’ or ‘pig’ or anything else that comes to mind. (Ideally something that makes sense though)

As for var max = -infinity, that’s just the developer’s way of saying,

I’m about to try to find the max value of this array. Assume that the max value is negative infinity so that any value bigger than that will count as the new ‘max’

Then they loop through the array to find a number bigger. Let’s say they find 0 first, so then max becomes 0 (because that is the biggest one they found so far)
Then they loop again and maybe they find 100 next, so then that becomes the new max.
Then later they find 5, 3, 20, 8 and none of those are bigger than 100 so they don’t become the max.
etc.

hope this helps

edit: and to be clear, the points array is definitely being passed into the function in this line
document.getElementById(“demo”).innerHTML = myArrayMax(points);

1 Like