Beginner15 minutesJavaScriptLevel 4

Loops in JavaScript

Learn how to repeat actions and iterate through data

Prerequisites: Before starting this tutorial, you should be familiar with JavaScript variables, data types, and control flow (if/else statements). If you're new to these concepts, check out our Variables & Data Types and Control Flow tutorials first.

Learning Objectives

By the end of this lesson, you'll be able to:

  • Explain Explain when to choose for, while, do...while, and for...of loops
  • Iterate through arrays and objects without off-by-one errors
  • Control loop execution with break and continue to guard edge cases
  • Build nested loops responsibly for grid or seating assignments
  • Troubleshoot infinite loops with clear exit conditions

Why This Matters:

These objectives emphasize practical repetition skills that unlock data handling, rendering lists, and asynchronous polling later in the track.

Introduction to Loops

Imagine you're a chef at the Black Swan Bistro, and you need to prepare 10 identical salads for a large party. Would you write out each step 10 times? Of course not! You'd create a process and repeat it 10 times.

Without Loops:

With Loops:

⏸️ Checkpoint: Loop Intentionality

Before moving forward, can you answer these?

  1. Which loop structure best fits the menu-prep scenario you just read?
  2. How would you detect and fix an infinite loop before it freezes the UI?
  3. Where could break or continue simplify your table-assignment logic?

Tips to Remember:

  • Sketch loop flow (init → condition → increment) before coding.
  • Log counters or array lengths while debugging long iterations.
  • Encapsulate loop bodies into helper functions when they grow.

How confident are you with this concept?

😕 Still confused | 🤔 Getting there | 😊 Got it! | 🎉 Could explain it to a friend!

The for Loop

The for loop is perfect when you know exactly how many times you want to repeat something. Think of it like a recipe with a specific number of servings.

Start: let i = 0i < length?Code Blocki++Done

For Loop Syntax

Parts of a for loop:

  • initialization: Sets up your counter variable (usually i)
  • condition: Checks if the loop should continue
  • increment: Updates the counter each time through the loop

Restaurant Example

The while Loop

Use a while loop when you don't know exactly how many iterations you need. It's like cooking pasta until it's al dente - you check the condition each time.

Condition?Code BlockDone

While Loop Example

The do...while Loop

A do...while loop is like a while loop, but it always runs at least once. Think of it as taking the first order of the day before checking if the restaurant is actually open.

Code BlockCondition?Done

Do...While Example

Loop Control Statements

Sometimes you need to change how your loop behaves. JavaScript provides two special statements:

break

Exits the loop completely

continue

Skips to the next iteration

Common Pitfalls

Watch Out For:

  • Infinite loops (forgetting to increment or update the condition)
  • Off-by-one errors (using < instead of <= or vice versa)
  • Modifying the loop variable inside the loop
  • Performance issues with very large loops

Practice Time!

Try These Exercises:

  1. Create a loop to display a restaurant menu (array of items)
  2. Use a while loop to simulate customers arriving until the restaurant is full
  3. Create a nested loop to assign tables (rows and columns)

Open your browser's console (F12) to try these exercises!

Lesson checkpoint

Test Your Knowledge

8 questions

Strengthen your understanding of Loops by answering the quiz below.

Loops Quiz

Test your understanding of Loops concepts.

Lesson Complete: What You Learned

Key Takeaways:

  • for loops are ideal when you know the exact number of iterations needed
  • while loops run as long as a condition is true—useful when the count is unknown
  • do...while loops guarantee at least one execution before checking the condition
  • break exits a loop immediately; continue skips to the next iteration
  • Always ensure loops have a clear exit condition to prevent infinite loops
  • Nested loops multiply iterations—use them carefully for grids or combinations

Learning Objectives Review:

Look back at what you set out to learn. Can you now:

  • ✅ Explain when to choose for, while, do...while, and for...of loops Check!
  • ✅ Iterate through arrays and objects without off-by-one errors Got it!
  • ✅ Control loop execution with break and continue to guard edge cases Can explain it!
  • ✅ Build nested loops responsibly for grid or seating assignments Could teach this!
  • ✅ Troubleshoot infinite loops with clear exit conditions Check!

If you can confidently answer "yes" to most of these, you're ready to move on!

Think & Reflect:

Loop Selection

Choosing the right loop structure signals intent. for loops suit counted iterations, while loops suit condition-driven repetition, and for...of loops suit iterating collections.
  • How do you decide which loop type fits a given task?
  • When would a for...of loop be more readable than a traditional for loop?

Safety & Performance

Always verify your exit condition before running a loop. For large arrays, consider early exits with break or functional methods like find and some that stop when a match is found.
  • What strategies help you avoid infinite loops?
  • How can you optimise loops that process large datasets?

🤔 Real-World Test:

Loops drive the core of data-heavy applications. Social media feeds loop through posts to render your timeline. E-commerce sites iterate over product catalogs to display search results. Game engines use loops to update every frame. Understanding loops means you can process any collection of data efficiently, from rendering UI lists to batch-processing API responses.

🎯 Looking Ahead:

Now that you can repeat actions efficiently, you're ready to learn about functions. In the next lesson, you'll discover how to package reusable blocks of logic, pass data in and get results back, and organize your code into clean, maintainable building blocks.

Recommended Next Steps

Continue Learning

Ready to move forward? Continue with the next tutorial in this series:

Functions

Related Topics

Explore these related tutorials to expand your knowledge:

Practice Projects

Apply what you've learned with these hands-on projects:

Todo List

Build a todo list with array iteration

JavaScriptLoopsArrays
Start Project

Photo Gallery

Create an image gallery with dynamic content

JavaScriptLoopsDOM
Start Project

Additional Resources

Deepen your understanding with these helpful resources:

Progress tracking is disabled. Enable it in to track your completed tutorials.