am93
September 7, 2021, 9:35pm
#1
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>
```

am93
September 7, 2021, 10:18pm
#3
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

am93
September 7, 2021, 10:23pm
#5
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.

am93:

` let len = arr.length;`

Set the `len`

variable equal to the length of the array.

am93:

` let max = -Infinity;`

Set the `max`

equal to negative infinity.

am93:

` while (len--) {`

Repeat this loop body while the variable `len`

is truthy before being decremented.

am93:

` if (arr[len] > max) {`

If the entry in the `arr`

ay at index `len`

is greater than the current `max`

am93:

` max = arr[len];`

then set `max`

to be the entry of the `arr`

ay at index `len`

am93:

` return max;`

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

am93
September 8, 2021, 4:47am
#7
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…

system
closed
March 10, 2022, 8:50am
#9
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.