Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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.

  2. 2

    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].

Back

6/12

  1. 1. The while Loop
  2. 2. Shorter Notation
  3. 3. The for Loop
  4. 4. Looping Through Arrays
  5. 5. Sum and Average
  6. 6. Counting
  7. 7. The Largest Value
  8. 8. The break Statement
  9. 9. The continue Statement
  10. 10. Loops and Text
  11. 11. Nested Loops
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.