# Min/Max array question

Can someone explain the myArrayMax(arr) function line by line? I understand that it loops throught the array and compares each value with the highest value found, but I don’t understand what some of the code in the function do. Thanks in advanced

``````<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>
``````

Why don’t you tell us what lines in particular you do not understand?

1 Like

Basically the whole function.

``````function myArrayMax(arr) { /*So this declares a function called
myArrayMax(arr)*/
var len = arr.length;/*arr.length is assigned to len, but I don't
know exactly what it does, it takes the whole array?*/
var max = -Infinity;//-Inf assigned to max but for what purpose
while (len--) { /*Basically this whole loop as well, I would like to
what each lines function is*/
if (arr[len] > max) {
max = arr[len];``````

If you don’t understand what this line is doing, I strongly suggest you start at the Basic JavaScript section of the Free Code Camp curriculum. You will learn a lot about various JavaScript built-in functions and object properties (like `length`).

99% of everything in the above lines of code are covered in the Basic JavaScript section.

If after completing the Basic JavaScript, you still have questions about the above code, ask again and explain what you do not understand.

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

function myArrayMax(arr) {
var len = arr.length; // length of the array, which is 6 if you have var points as the arguments.
var max = -Infinity; // set the lowest possible number to max, in case var points contains all negative numbers.
while (len--) { // start from 6 and decrease by 1 each loop.
if (arr[len] > max) { // if arr[5] *first iteration which is 10* greater than -Infinity
max = arr[len]; // set 10 to max
}
} // continue the iteration
return max; // return the max number
}
``````

This is a good site to “see” what you code is doing: website

3 Likes

Thank you! the site you recommended doesn’t seem to work well tho, do you know any other sites that analyzes code?

Try the regular visualizer maybe:
http://pythontutor.com/visualize.html