← Back to Programming Fundamentals
08

Loops and Repetition: Avoid Repeated Work with `for` and `while`

Learn to repeat tasks in a controlled way with `for` and `while`, understanding what is repeated, when it stops, and how the changing value evolves on each iteration.

📘 Theory

Why Loops Exist

A loop prevents you from copying the same action many times when only the state of each repetition changes.

1

If you want to show the numbers from 1 to 5, you could write five `console.log()` statements. But that does not scale and does not teach the program how to repeat with intention.

2

A loop solves that: it defines a repetition, a control rule, and a stopping point.

The `for` Loop: When You Know How Many Times You Want to Repeat

A `for` loop fits well when you have a clear counter or a planned number of repetitions.

  • Start: where the counter begins.
  • Condition: how long the repetition continues.
  • Update: how the counter changes each time.

The `while` Loop: Repeat While a Condition Stays True

`while` is useful when repetition depends more on a condition than on a fixed count.

1

In this case the program keeps entering the block as long as the condition remains `true`.

2

Because the state update happens inside the block, it is even more important not to forget changing the control variable.

Common Mistakes and Helpful Habits

The typical failure is not the loop itself. It is losing track of what makes it advance and what makes it stop.

  • Forgetting to update the control variable.
  • Writing a condition that never stops being true.
  • Not logging the counter while learning.
  • Not testing a small range before generalizing.

🧪 Learn by doing

Example Guided Example: A Countdown Use a `for` loop to repeat an output with a clear counter.

🏁 Challenges

Challenge Challenge: Print 1 to 4 Without Manual Repetition Create a loop that shows four values in order with one repetition structure.

🧰 Resources

Test

Check your knowledge with a test about Programming Fundamentals.

Test for Programming Fundamentals

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com