Search⌘ K
AI Features

For Loops and Arrays

Explore how to use for loops and arrays in JavaScript by building a weekly step tracker. Learn to store daily steps in an array, sum them with loops, calculate averages, and identify the day with the highest count. This lesson helps you handle repeated data efficiently and display results dynamically on a web page.

The project

You’ve already created a step tracker that records daily steps. Right now, it only works when you enter the numbers manually. Printing a single line, such as Steps today: 3,000, can be useful, but it doesn’t show your progress for the entire week. To do that, you need a system that stores seven days of step counts in an array and loops through them to calculate the total and the average.

Your project: build a weekly step tracker that keeps 7 days of steps in an array, uses a loop to add them up, and calculates the average steps per day.

The programming concept

A while loop repeats as long as a condition is true. But sometimes you already know exactly how often you want something to repeat. For example, say you want to print “Hello” five times. Which loop feels more natural here: a for loop or a while loop?

In JavaScript, the for loop can work in two modes:

  • For loop with a range: Runs a fixed number of times, e.g., for (let i = 0; i < 5; i++) repeats 5 times. ...