Repeating with for Loops

Doing something many times without copy-paste

11 min read · runnable Javascript

Imagine you want to print the numbers 1 to 5. You could write five console.log lines, but that gets tedious fast. A loop repeats code for you.

The most common is the for loop. It looks busy at first, but it has just three parts separated by semicolons.

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

The three parts inside the brackets are:

  1. let i = 1 the start: create a counter called i beginning at 1.
  2. i <= 5 the condition: keep looping while this is true.
  3. i++ the step: add 1 to i after each loop. (i++ is shorthand for i = i + 1.)

So this loop runs with i equal to 1, then 2, 3, 4, 5, printing each one, then stops because 6 <= 5 is false.

Looping over an array

Loops and arrays are best friends. Use the counter as the index to visit every item:

let fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Here we start at 0 (the first index) and continue while i is less than the array's length.

Tip: Using i < fruits.length means your loop automatically works no matter how many items the array has. No need to count them by hand.

Try it yourself

Run the loop, then try changing the numbers or adding items to the array.

Try it yourself
Output
Press “Run code” to see the result.

Quick check

Q1 What does i++ do inside a for loop?

Q2 Why do we usually start the counter at 0 when looping over an array?

Want to save your progress? It's free.

Create a free account