What do these two expressions mean?

This is an example on w3schools, but it’s not clear what -Infinity or len-- mean. I tried Googling it but it’s not picking it up. Can you please explain? Thanks

source: Tryit Editor v3.7

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The highest number is <span id="demo"></span>.</p>

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

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

</body>
</html>

The doesn’t seem to be mentioned here. What is it’s role in relation to infinity?

The - is just a negative sign. Just like -5 is negative 5, -Infinity is negative infinity.

1 Like

So while were subtracting from the length of the arr, if the length of array is greater than negative infinity, max = arr at the index of len?

No.

Set the len variable equal to the length of the array.

Set the max equal to negative infinity.

Repeat this loop body while the variable len is truthy before being decremented.

If the entry in the array at index len is greater than the current max

then set max to be the entry of the array at index len

And return the value of max once the loop body concludes.


The style makes this a bit confusing, but this is basic control structures and syntax, except for the bit about truthiness.

I’m not sure where you found this code, but I would call it bad code. Don’t do this. The code style makes this harder than it should be.

1 Like

Thank you. It was on w3schools. Not sure why they used a confusing example like this especially when it’s part of an introductory tutorial

That should tell you something about some of the W3Schools content…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.