Start learning free

LESSON 269 OF 671 · DESTRUCTURING, SORTING & BUILT-INS

Min, Max and Sum in JavaScript

Lesson

TL ; DR:

Math.min(...arr) gives the smallest value of an array.

Math.max(...arr) gives the largest value.

reduce adds all the values up.


let prices = [4, 9, 2, 7];

console.log(Math.min(...prices));    // 2

console.log(Math.max(...prices));    // 9

let total = prices.reduce((sum, x) => sum + x, 0);

console.log(total);                  // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. JavaScript has ready-made tools for them.

Math.min and Math.max compare separate numbers, as in Math.max(3, 8). You used Math.max this way in Maximum Number In Array. The three dots in ...prices spread the array out into separate numbers. So Math.max(...prices) is the array's largest value.

Don't forget the dots. With two or more prices, Math.max(prices) gives NaN, which means "not a number".

JavaScript has no sum function. The array method reduce does the job:

let total = prices.reduce((sum, x) => sum + x, 0);

The arrow function gets the running sum and the next value x. It returns the new sum. The reduce method calls it once per value, from left to right. The 0 at the end is where the sum starts.

Watch out for an empty array. Math.max(...[]) is -Infinity. Math.min(...[]) is Infinity. You get no error, just a strange number. Check arr.length first.

reduce on an empty array gives its start value, 0. Without that 0, it throws a TypeError. So always pass it.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check