Loops (for, while, for...of)
Master loops in JavaScript! Learn for, while, do-while, for...of, and for...in loops to repeat code efficiently.
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:
- Initialize a counter.
- Check a condition.
- Run the code.
- Update the counter.
- 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)
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) { ... }
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);
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.
for...in (Objects)
Best for: Objects. It gives you the keys (property names).
6. Controlling Loops: break & continue π
break: Exits the loop immediately.continue: Skips the current iteration and moves to the next one.
Practical Example: Data Processor π
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 4Which loop is best for iterating over an array's values?
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! π