JavaScript Basics: Your First Programs
Loops
In this lesson you will
- Write a for loop and a while loop
- Loop through the items of an array with for...of
- Use break and continue
Introduction
Imagine writing "I will listen carefully" 100 times. You would get tired quickly. A computer would not. You tell it once to repeat. That is what a loop does.
The simple explanation
A loop repeats a block of code.
The for loop
A for loop has three parts in the brackets, separated by semicolons:
- Start:
let i = 1creates a counter. - Condition:
i <= 5keeps looping while this is true. - Step:
i++adds 1 to the counter after each round.
The code in the curly braces runs once for each round. i++ is shorthand for i = i + 1.
Quick quiz
How many times does for (let i = 0; i < 3; i++) run its body?
Adding things up
Loops are great for building a result step by step.
This adds 1 + 2 + 3 + 4 + 5 and prints 15.
The while loop
A while loop keeps going as long as its condition is true. Use it when you do not know in advance how many rounds you need.
Be careful: if the condition never becomes false, the loop never ends. Try changing n * 2 to n and running it. This site will stop the program after a few seconds.
for...of
To go through the items of an array, for...of is the cleanest way.
break and continue
breakstops the loop completely.continueskips the rest of this round and moves to the next.
It prints 1, 2, 4 and 5: it skips 3, and stops before printing 6.
Quick quiz
What does break do inside a loop?
Try it yourself
Print the numbers 1 to 10, but only the even ones. Hint: use % and an if inside the loop.
Summary
- A loop repeats code.
foris great when you know the number of rounds. whilerepeats as long as a condition is true. Make sure it can end.for...ofwalks through an array.breakstops a loop andcontinueskips a round.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading