Putting it together
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Putting it together
- Real programs combine variables, loops, functions, arrays and objects.
- A
for...ofloop reads each item of an array directly — no index needed.
function total(nums) {
let t = 0;
for (const n of nums) {
t = t + n;
}
return t;
}
console.log(total([4, 8, 6])); // → 18
Explore
for...of builds the total
for...of reads each item directly. Watch t add them up, one at a time.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
function countAbove(nums, limit) {
let count = 0;
for (const n of nums) {
if (n > limit) {
count++;
}
}
return count;
}
console.log(countAbove([3, 7, 2, 8], 4)); // → 2
Common mistakes
- Build in small steps and use
console.logto check as you go. - Keep the HTML, CSS and JavaScript doing their own jobs.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Write a function total(nums) that returns the sum of every number in the array nums.
Click Run to see the output here.
Write a function biggest(nums) that returns the largest value in the array.
Click Run to see the output here.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit.
Click Run to see the output here.