Functions and Arrays
An argument can be any value, an array too. A function that gets an array can go through it with a loop and return a result. This function adds up all the numbers in an array:
function sum(numbers) {
let total = 0;
for (const number of numbers) {
total += number;
}
return total;
}
console.log(sum([1, 2, 3]));
const prices = [120, 45, 80];
console.log(sum(prices));This prints:
6
245The parameter numbers holds whatever array the call passes: first [1, 2, 3], then the array prices. You know the loop from the lesson on loops, but now it's inside a function, so you can add up any array with a single line. And because total is a local variable, every call starts from 0 again.
Notice where the return is: after the loop, when all the numbers have been added up. A common mistake is to put it inside the loop:
function sum(numbers) {
let total = 0;
for (const number of numbers) {
total += number;
return total;
}
}
console.log(sum([1, 2, 3]));This prints:
1return ends the whole function, and the loop with it, already in the first iteration. So the function returns just the first number.
Instructions
The program ends with the error ReferenceError: average is not defined, because the function average doesn't exist yet. Write it in place of the comment: it has a parameter numbers and returns the average of the numbers in the array. Add them up with a loop and divide the sum by the number of elements, numbers.length. The program then prints the average temperatures of two weeks, 21 and 13.
At the end of the program, compare the two weeks: if the average of week1 is higher than the average of week2, print Week 1 was warmer.
Start programming for free
8/10