The Largest Value
The third pattern finds the largest value. Imagine going through a pile of exam papers to find the best one. You pick up the first paper. Then you look at the others one by one, and whenever one is better than the paper in your hand, you take that one instead. At the end, you are holding the best paper. In code, the paper in your hand is a variable:
const scores = [72, 45, 90, 38, 64];
let highest = scores[0];
for (const score of scores) {
if (score > highest) {
highest = score;
}
}
console.log("Highest score:", highest);Highest score: 90The variable highest starts with the first element. Then the loop compares each score with it: 72 is not greater than 72, 45 isn't either, but 90 is, so highest becomes 90. Neither 38 nor 64 is greater than 90, so 90 stays until the end. Because highest changes, it must be a let.
Why not start with 0? Because 0 might not be one of the values. If all the values were negative, for example winter temperatures [-5, -2, -8], the starting 0 would remain the largest, and the program would print 0, a temperature that isn't in the array at all. The first element is always a safe start.
You find the smallest value the same way, only with < instead of >.
Instructions
- 1
The array
pricesholds the prices of headphones in an online shop. Create a variablehighestwith the first price,prices[0]. - 2
Go through
priceswith a loop, and whenever a price is greater thanhighest, store it inhighest. After the loop, printconsole.log("Most expensive:", highest);. The output isMost expensive: 2499. - 3
Find the cheapest headphones the same way, with a variable
lowest, and print the price withconsole.log("Cheapest:", lowest);. The output isCheapest: 179.