Repeating with for Loops
Doing something many times without copy-paste
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:
let i = 1the start: create a counter calledibeginning at 1.i <= 5the condition: keep looping while this is true.i++the step: add 1 toiafter each loop. (i++is shorthand fori = 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.
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.
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