Mark As Completed Discussion

Using a JavaScript Loop

Now for the comparison part, we will now compare the values inside our array to find the maximum and minimum values of our array using a For Loop

JAVASCRIPT
1for(let number of numbers){
2    if(number > maximum)
3        maximum = number
4        
5    if(number < minimum)
6        minimum = number
7 }
8 
9console.log(
10  `Maximum Value: ${getMaxOfArray(numbers)}` + `\nMinimum Value: ${getMinOfArray(numbers)}`
11)

The loop statement will loop through our array of numbers, number is the value that is being processed each time starting from the first number in our array which is 4 then 12 ... 7 ... until it reaches the final number of the array, 15.

For Loop: Maximum Value

If the number that is being processed is higher (>) than the maximum value that we have currently then the number being processed will become the new maximum value.

Initially since the maximum value is -∞, in the first loop the first number of our array will become the maximum number since all numbers are greater than -∞ (the current maximum value). In our case it will become 4.

The second loop will then run where the second number in our array (12) will be compared to our current maximum value (4). Since 12 > 4 the maximum value will now become 12 and the third loop will begin. The For Loop will continue until the last number in our array has been processed.

Using Loops

For Loop: Minimum Value

The exact same mechanism will happen for the minimum value except if the number that is being processed is less (<) than the minimum value that we have currently then the number being processed will become the new minimum value.

Using Loops

Console output

To finish the console will output the maximum and the minimum:

Using Loops
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment