RivoCode

JavaScript Fundamentals · Loops · Lesson 9 of 48

for Loops

Concept

for Loops

A for loop repeats code a set number of times using a counter. It's the most common loop when you know in advance how many times you need to repeat something.

A for loop packs three steps — where to start, when to stop, and how to move forward — into a single, easy-to-scan line, instead of spreading them across separate statements.

By the end of this lesson
  • Explain the core idea behind for Loops.
  • Predict output before running a change.
  • Test one realistic and one unusual input.
  • Use the result to make the next decision.
How to study this page
  1. 1. Read one concept.
  2. 2. Change the example.
  3. 3. Run, compare, and explain.
  4. 4. Complete the challenge below.
Syntax
for (initializer; condition; increment) {
  // code to repeat
}
ExampleRunnable
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
Try it Yourself »
Counting down instead of up
for (let i = 5; i >= 1; i--) {
  console.log(i);
}
Skipping every other number
for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}
Note: The increment step doesn't have to be i++ — any expression that changes i works, including i += 2 to step by twos.

Good to know

All three parts of a for loop are optional — for (;;) creates an infinite loop, easy to create by accident if you forget the increment.

Self-check before continuing

Without looking at the example, describe what changes when you modify one input in for Loops. Then reopen the editor and prove your explanation with a small test.

You are ready to continue when you can predict, test, and explain the result.

Your turn

Use a for loop to print the numbers 10 down to 1.

Loading editor…

Console

Output will appear here...