Loops in Node.js
Learn how loops work in JavaScript: how execution flows, when loops stop, and how to choose the right loop for the job.
Introduction to Loops
A loop allows the same block of code to run multiple times. Instead of writing the same code again and again, a loop repeats it automatically based on a condition.
1. Why Loops Are Needed
Loops remove repetition.
for Loop
The for loop is used when you know how many times you want to repeat something.
1. How a for Loop Works Internally
Execution order matters.
2. Traversing an Array using for
Access elements using index.
while Loop
The while loop is used when you do not know in advance how many times the loop will run.
1. How while Loop Works
Condition-driven repetition.
do...while Loop
The do...while loop guarantees one execution, even if the condition is false.
1. do...while Execution
Body runs before condition check.
for...of Loop
for...of is the easiest way to loop over arrays and other iterables.
1. for...of with Arrays
Value-based looping.
for...in Loop
for...in is designed for objects, not arrays.
1. for...in with Objects
Key-based iteration.
break & continue
break and continue change the normal loop flow.
1. break
Exit loop immediately.
2. continue
Skip current iteration.
Guard Clauses in Loops
Guard clauses prevent deep nesting and make loops easier to read.
1. Guard Clause using continue
Skip invalid data early.
Best Practices
Choosing the correct loop improves clarity and prevents bugs.
1. Loop Selection Guidelines
Rules of thumb.
Reverse for Loop
Reverse loops are useful when removing items, countdowns, or processing data from end to start.
1. Reverse for Loop on Numbers
Count down instead of up.
do-while vs while
A do-while loop guarantees at least one execution. This behavior can be simulated using while.
1. do-while Logic using while
Manual first execution.
forEach on Arrays & Strings
forEach is available on arrays. Strings must be converted first.
1. forEach on Arrays
Callback runs once per element.
2. forEach on Strings (via split)
Strings are not directly supported.
forEach on Maps & Objects
Maps support forEach directly. Objects require conversion.
1. forEach on Map
Maps have built-in forEach.
2. forEach on Object (via Object.entries)
Objects do not support forEach directly.