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
The array prices holds the prices of headphones in an online shop. Create a variable highest with the first price, prices[0].
Go through prices with a loop, and whenever a price is greater than highest, store it in highest. After the loop, print console.log("Most expensive:", highest);. The output is Most expensive: 2499.
Find the cheapest headphones the same way, with a variable lowest, and print the price with console.log("Cheapest:", lowest);. The output is Cheapest: 179.
Start programming for free
7/12