To the Max explainer


#1

The aim of this puzzle: Find the largest number in the array using a loop and the larger() function.

Walkthrough of the solution: To find the maximum of a list, you can compare the first 2 items and store larger one as the current maximum. Then you compare that current maximum to the 3rd item, and store the larger one. Then continue until you’ve compared each item to the current maximum. In the end, the maximum will be the largest value from the array.

The larger() function takes in 2 numbers and will output the larger one. The maximum() function starts by creating a max variable that will store the current maximum, but it will start at 0 for now. The loop will go through each item in the array and hold it in a variable called num. What we need to do is compare the num to the max and store the larger one as the new max.

Instead of max = num, we need to use max = larger(max, num). You can also switch the order of the arguments.

Sample code solution:
(Tap below to reveal)

function larger(a, b) {
  return a > b ? a : b;
}

function maximum(array) {
  let max = 0;
  for (let num of array) {
    max = larger(max, num);
  }
  return max;
}
console.log(list);
console.log(maximum(list));

JavaScript Concepts: Binary Expression (>), Code Block (function), Conditionals (ternary statement), console.log(), Code Block (for loop)