JavaScript Loops
# JavaScript Loops
Imagine you need to write "I will not talk in class" 100 times on a chalkboard. Doing it by hand is exhausting. In programming, whenever we need to repeat an action, we use Loops.
In this chapter, we will learn how to make the computer do the heavy lifting of repetitive tasks effortlessly.
1. Introduction
Loops are used to execute a block of code a number of times. This is incredibly useful when working with lists of data (like a list of users, products, or messages) or when you want an animation to repeat over and over.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Use the
forloop to run code a specific number of times.
-
Use the
whileloop to run code as long as a condition is true.
-
Understand the
do...whileloop.
-
Use the
breakstatement to exit a loop early.
-
Use the
continuestatement to skip an iteration.
- Build a Multiplication Table Generator mini-project.
3. The for Loop
The for loop is the most common loop. You use it when you know exactly how many times you want the code to run.
It has three parts inside its parentheses, separated by semicolons:
- 1. Initialization: Run once before the loop starts (e.g., set a counter).
- 2. Condition: Checked before every run. If true, the loop runs. If false, it stops.
- 3. Increment/Decrement: Run after every loop cycle (e.g., increase the counter).
4. The while Loop
The while loop loops through a block of code as long as a specified condition is true. You use this when you don't know exactly how many times the loop should run, but you know when it should stop.
5. The do...while Loop
This is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
---
6. Real-world Examples & Code Snippets
Example 1: Basic for Loop
Let's print numbers 1 to 5.
Output Explanation:
-
let i = 1sets our counter.
-
i <= 5ensures it runs untilibecomes 6.
-
i++adds 1 toiafter every cycle.
Example 2: Counting Backwards
You can decrement (i--) instead of incrementing.
Example 3: The while Loop
Let's do the same 1 to 5 count using a while loop.
Example 4: do...while Guarantee
The do...while loop always runs at least once, even if the condition is totally false.
Example 5: The break Statement
The break statement "jumps out" of a loop entirely, terminating it immediately.
Output Explanation: Prints 1, 2, 3, 4, then breaks.
Example 6: The continue Statement
The continue statement "jumps over" one iteration in the loop, but continues with the next iteration.
Output Explanation: Prints 1, 2, "Skipping 3!", 4, 5.
Example 7: Looping to create HTML
This is where loops become very powerful in web development.
Output Explanation: Generates three <li> elements dynamically and inserts them into the <ul>.
Example 8: Nested Loops
A loop inside a loop. The inner loop runs completely for *every* single iteration of the outer loop.
Output Explanation: Prints Row 1 Col 1, Row 1 Col 2, Row 2 Col 1, Row 2 Col 2, etc.
Example 9: The Infinite Loop Warning
If you forget to increment your counter in a while loop, or create a condition that can never be false, your browser will crash.
Example 10: Loop with User Input
Using a while loop to enforce input rules.
Output Explanation: The prompt will keep reappearing until the user types exactly "secret123".
---
7. Common Mistakes for Beginners
-
1.
Infinite Loops: Forgetting
i++in awhileloop or writing a condition likei > -1wheniis increasing. This freezes the browser tab.
-
2.
Off-by-One Errors: Writing
i < 10when you actually wanted to include 10 (which requiresi <= 10).
-
3.
Using commas instead of semicolons in a
forloop:for (let i=0, i<5, i++)will throw a syntax error. It must be semicolons:for (let i=0; i<5; i++).
8. Best Practices
-
Use
forloops when you know the exact number of iterations (e.g., counting from 1 to 10).
-
Use
whileloops when the number of iterations is unknown and depends on an external condition (e.g., waiting for user input to be correct).
- Keep loop logic as simple as possible. Heavy calculations inside a loop that runs thousands of times will slow down your website.
9. Mini Project: Multiplication Table Generator
Let's build a tool that generates a math multiplication table dynamically using a for loop.
HTML:
table.js:
10. Exercises
-
1.
Write a
forloop that logs all even numbers from 2 to 20 to the console.
-
2.
Write a
whileloop that counts down from 5 to 1, then console logs "Happy New Year!".
-
3.
Create a
forloop from 1 to 10. Inside it, use anifstatement and thecontinuekeyword to skip the number 7.
11. MCQs (Multiple Choice Questions)
Q1: Which loop is guaranteed to run its code block at least once? A) for loop B) while loop C) do...while loop D) none of the above *Answer: C*
Q2: What is the correct syntax for a for loop?
A) for (let i = 0; i < 5; i++)
B) for (let i = 0, i < 5, i++)
C) for i = 1 to 5
D) loop (i < 5)
*Answer: A*
Q3: Which keyword stops a loop entirely? A) stop B) exit C) break D) continue *Answer: C*
12. Interview Questions
Q: Explain the difference between break and continue.
*A: break completely terminates the loop and moves the program execution to the code immediately following the loop. continue only terminates the current iteration of the loop, skipping any remaining code in that specific cycle, and jumps back to evaluate the loop's condition for the next iteration.*
Q: What causes an infinite loop and why is it dangerous in JavaScript? *A: An infinite loop occurs when the loop's terminating condition is never met (e.g., a counter is never incremented). In JavaScript, since it is a single-threaded environment, an infinite loop blocks the main thread, freezing the UI and preventing any other code from running until the browser crashes or intervenes.*
13. FAQs
Q: Can I put variables inside the loop's condition that come from outside?
*A: Yes! for(let i=0; i < someExternalVariable; i++) is extremely common.*
14. Summary
- Loops automate repetitive tasks.
-
forloops require initialization, condition, and increment logic.
-
whileloops run as long as a condition remains true.
-
do...whileloops always execute at least one time.
-
breakescapes the loop entirely;continueskips the current iteration.