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 longWords(words) {
const result = [];
for (const w of words) {
if (w.length >= 5) {
result.push(w);
}
}
return result;
}
console.log(longWords(["cat", "apple", "sun", "banana"])); // → ["apple", "banana"]
w |
w.length >= 5? |
result after |
|---|---|---|
"cat" |
no | [] |
"apple" |
yes | ["apple"] |
"sun" |
no | ["apple"] |
"banana" |
yes | ["apple", "banana"] |
resultstarts as an empty array before the loop, and the function returns it after the loop.
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, a total or a flag as you go.
- A flag starts
falseand becomestrueat the first match. Once you know the answer,returnit straight away.
function hasNegative(nums) {
for (const n of nums) {
if (n < 0) {
return true; // found one: stop now
}
}
return false; // only after checking every item
}
console.log(hasNegative([3, -1, 4])); // → true
console.log(hasNegative([2, 5])); // → false
function average(scores) {
let sum = 0;
for (const s of scores) {
sum += s;
}
return sum / scores.length;
}
console.log(average([70, 85, 90])); // → 81.66666666666667
Common mistakes
- Build in small steps and use
console.logto check as you go. - Set a running total to
0(or a list to[]) before the loop, not inside it, or it starts again every time round. return falseinside the loop, in anelse, stops after the first item. Returnfalseonly after the loop has checked everything.- For the largest value, start with the first item (
nums[0]), not0: with[-5, -2], starting at0would wrongly give0.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write a function total(nums) that returns the sum of every number in the array nums.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write a function biggest(nums) that returns the largest value in the array.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit.
Click Run to see the output here.