JavaScript

Loops (for, while, for...of)

Master loops in JavaScript! Learn for, while, do-while, for...of, and for...in loops to repeat code efficiently.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Master loops in JavaScript! Learn for, while, do-while, for...of, and for...in loops to repeat code efficiently. This hands-on tutorial focuses on practical implementation of loops (for, while, for...of) concepts.

Loops

Loops allow you to repeat a block of code multiple times. They are essential for automating repetitive tasks and processing collections of data.

1. Why Loops? πŸ”„

What is it? A control structure that repeats code until a specified condition is met.

Why use it? Imagine you need to print numbers from 1 to 100. Writing console.log(1), console.log(2)... is tedious. Loops do this in 3 lines.

How it works:

  1. Initialize a counter.
  2. Check a condition.
  3. Run the code.
  4. Update the counter.
  5. Repeat until condition is false.

2. The for Loop 🎯

Best for: When you know exactly how many times you want to loop.

Syntax: for (initialization; condition; increment)

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

3. The while Loop πŸ”

Best for: When you don't know how many times to loop (e.g., "keep asking until user enters correct password").

Syntax: while (condition) { ... }

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

4. The do...while Loop πŸ”„

Best for: When you need the code to run at least once, regardless of the condition.

Syntax: do { ... } while (condition);

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

5. Modern Loops: for...of & for...in 🎨

ES6 introduced cleaner ways to loop through data.

for...of (Iterables)

Best for: Arrays, Strings, NodeLists. It gives you the values.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

for...in (Objects)

Best for: Objects. It gives you the keys (property names).

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

6. Controlling Loops: break & continue πŸ›‘

  • break: Exits the loop immediately.
  • continue: Skips the current iteration and moves to the next one.
JAVASCRIPT PLAYGROUND
⏳ Loading editor…

Practical Example: Data Processor πŸ“Š

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "JavaScript loops, for, while, do-while, for...of, for...in, break, and continue"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 4

Which loop is best for iterating over an array's values?

for...in
for...of
while
do...while

Key Takeaways

βœ… for: Standard loop, good for counting.
βœ… while: Good when iteration count is unknown.
βœ… for...of: Best for Arrays (Values).
βœ… for...in: Best for Objects (Keys).
βœ… break / continue: Control flow within loops.

What's Next?

Now that you can repeat code, let's learn how to organize it into reusable blocks with Functions!

Keep coding! πŸš€