Putting It All Together
Combining variables, loops, and functions
You now know variables, strings, numbers, booleans, arrays, if/else, loops, and functions. Let's see how they work as a team in one small program.
Here is a program that looks at a list of test scores and reports how many passed.
let scores = [55, 80, 42, 91, 68];
function isPass(score) {
return score >= 50;
}
let passes = 0;
for (let i = 0; i < scores.length; i++) {
if (isPass(scores[i])) {
passes++;
}
}
console.log(`${passes} out of ${scores.length} passed.`);How it fits together
- An array holds all the scores.
- A function decides whether one score is a pass.
- A loop visits every score in the array.
- An if checks each score using the function.
- A variable (
passes) keeps a running count.
This pattern of looping over a list, checking a condition, and counting is something you will use again and again in real programs.
Tip: When a program feels big, break it into the small ideas you already know. Each piece here is something you have practised in earlier lessons.
Try it yourself
Change the scores or the pass mark inside isPass and watch the result update.
Try it yourself
Output
Press “Run code” to see the result.
Quick check
Q1 In the program, what is the variable passes used for?
Want to save your progress? It's free.
Create a free account