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.
🎯 🔁 Prep Like a Pro Line Cook
Imagine prepping 50 identical salads before guests arrive. You could write each instruction separately, or you could repeat the same block with a loop. Restaurants thrive on repeatable systems—so do JavaScript apps.
- Where do you perform the same action more than twice in your projects?
- What happens when you forget to stop a repetitive task (like a timer or subscription)?
- How could loops help you explore large datasets or UI collections faster?
This lesson helps you convert repetitive work into efficient loops so data lists, UI grids, and API responses become effortless to process.
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?
- Which loop structure best fits the menu-prep scenario you just read?
- How would you detect and fix an infinite loop before it freezes the UI?
- 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.
For Loop Syntax
Parts of a for loop:
initialization: Sets up your counter variable (usuallyi)condition: Checks if the loop should continueincrement: 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.
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.
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:
- Create a loop to display a restaurant menu (array of items)
- Use a while loop to simulate customers arriving until the restaurant is full
- 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
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
- 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
- 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
Related Topics
Explore these related tutorials to expand your knowledge:
Practice Projects
Apply what you've learned with these hands-on projects:
Additional Resources
Deepen your understanding with these helpful resources:
- MDN: Loops and iteration - Complete guide to JavaScript loops
Progress tracking is disabled. Enable it in to track your completed tutorials.
Cookie Settings