Loops
Programs often need to repeat the same action more than once.
Instead of writing the same code again and again, you can use a loop to repeat a block of code for you.
What a loop is
A loop repeats a block of code.
It can repeat for a set number of times, or while a condition is true.
When the condition becomes false, the loop stops and JavaScript moves on to the next part of the program.
Why loops are useful
Loops save time and help you avoid repeated code.
For example, if you want to show a message 100 times, you should not write 100 separate console.log() lines.
With a loop, you write the message once and control how many times it repeats.
First code example
The for loop is commonly used for counting and repeated actions.
for (let count = 1; count <= 3; count++) {
console.log("This is message number " + count);
}When you click Run, you will see three messages in the Output section.
Code walkthrough
The for loop has three parts inside the parentheses.
They are separated by semicolons ;.
let count = 1is the starting value. It creates a counter variable and starts it at1.count <= 3is the condition. The loop runs while this condition is true.count++is the update. It increasescountby1after each repeat.
The code inside the curly braces {} runs each time the loop repeats.
When count becomes 4, the condition count <= 3 is false, so the loop stops.
Changing how many times a loop runs
You can change the starting value or condition to control how many times a loop runs.
This example counts from 5 to 10.
for (let i = 5; i <= 10; i++) {
console.log("Counting: " + i);
}JavaScript also has a while loop. A while loop repeats code while a condition is true.
For this beginner lesson, focus on for loops because they are useful when you know how many times you want to repeat an action.
Warning: Make sure your loop can stop. If the condition never becomes false, the loop can run forever and freeze the page.
Mini task
Change the code block below so it prints the numbers from 1 through 5 instead of 1 through 2.
for (let count = 1; count <= 2; count++) {
console.log(count);
}Short quiz
Question: What happens when a loop condition becomes false?
- A) The loop restarts from the beginning.
- B) The loop stops running.
- C) The loop becomes infinite.
Answer: B. The loop stops running.
Small challenge
Write a for loop that prints "Hello" exactly four times.
// put your code below
console.log()Summary
- A loop repeats a block of code.
- A
forloop is useful for counting and repeated actions. - A basic
forloop has a starting value, a condition, and an update. - The loop stops when the condition becomes false.
- A loop must have a way to stop, or it can become an infinite loop.