How does the while loop gets the maximum value from the passed list in this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How does the while loop gets the maximum value from the passed list in this code?

I'm new to JavaScript. While Learning from w3schools, i found the following code block, but I didn't understand anything. Can you please explain me, why & how the following code works. I only want to know how does while loop work here . Specially, The Condition Of The loop. The code block from W3Schools: 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; }

15th Nov 2020, 8:43 AM
Noob Programmer
Noob Programmer - avatar
2 Answers
+ 3
Abir Sheikh , the loop goes backwards and it stores the current element in max variable, in each next iteration first it check if the value is bigger than the max, if it is in the max is stored this value, if not the loop continues.
15th Nov 2020, 8:48 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
@TheWhiteCat Can you please explain the condition used here ( len-- )? How did it work?
15th Nov 2020, 8:52 AM
Noob Programmer
Noob Programmer - avatar