Counting

The second pattern counts: how many elements of an array meet a condition? It looks like adding up, but instead of the value, you add 1, and only when an if says so:

const temperatures = [18, 24, 27, 15, 31, 22, 29];
let hotDays = 0;
for (const temperature of temperatures) {
    if (temperature >= 25) {
        hotDays++;
    }
}
console.log("Hot days:", hotDays);
Hot days: 3

The counter hotDays starts at 0, before the loop. The loop looks at every temperature, and the if decides whether to count it. hotDays++ runs only for 27, 31 and 29, so at the end, the counter is 3. Again, you print the result after the loop.

Sometimes you want to know not only how many, but also which ones. Then start with an empty array and .push() each matching element into it:

const temperatures = [18, 24, 27, 15, 31, 22, 29];
const hot = [];
for (const temperature of temperatures) {
    if (temperature >= 25) {
        hot.push(temperature);
    }
}
console.log("Hot temperatures:", hot);
console.log("Hot days:", hot.length);
Hot temperatures: [27, 31, 29]
Hot days: 3

The array hot can be a const: you add elements to it, but you never store a different array in the variable.

Instructions

The array scores holds the points from a test. You pass with 50 points or more. Count the students who passed: create a variable passed with the value 0, go through scores with a loop, and for every score of at least 50, increase passed by one with ++. After the loop, print console.log("Passed:", passed);. The output is Passed: 5.

Now also collect the scores below 50: before the loop, create an empty array failed, and inside the loop, add each score below 50 to it with .push() (an else will do). After the loop, print it with console.log("Failed:", failed);. The output is Failed: [45, 38, 29].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/12