Loops are one of the most powerful features in JavaScript. They allow developers to execute a block of code repeatedly, making tasks like iterating over arrays, objects, or performing repetitive calculations much easier. In this post, we’ll explore the different types of loops in JavaScript, their syntax, and when to use each
1- for Loop
Uses: When you know number of iteration.
<script>
for (let i = 0; i < 5; i++) {
console.log(i);
}
</script>
Initializes a counter, checks a condition, and updates the counter after each iteration.
2- while Loop
Uses: When the number of iterations is unknown and depends on a condition.
<script>
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
</script>
Runs as long as the condition evaluates to true
3- do ... while Loop
Uses: When you want the loop to run at least once, regardless of the condition
<script>
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
</script>
Executes the block first, then checks the condition.
4- for ... in Loop
Uses: Iterating over the properties of an object.
<script>
const obj = {a:1, b:2, c:3};
for (let key in obj) {
console.log(key, obj[key]);
}
</script>
Returns keys of an object, which can be used to access values.
5- for...of Loop
Uses: Iterating over iterable objects like arrays, strings, maps, and sets.
<script>
const arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
</script>
Returns values directly from the iterable
6- foreach Loop Method (Array-specific)
Uses: Cleaner iteration over arrays using callback functions
<script>
[1, 2, 3].forEach(num => console.log(num));
</script>
Quick Table
| Loop Type | Use Case |
|---|
for | Fixed number of iterations |
while | Condition-based, unknown iterations |
do...while | At least one guaranteed execution |
for...in | Object properties |
for...of | Iterable values (arrays, strings, sets) |
forEach() | Functional array iteration |
🙏 Thank You for Reading!
Thank you for taking the time to read this blog!
If you have any questions or need help with something, feel free to drop a message in the comments or contact section. I’ll get back to you as soon as possible.
Happy Learning! 😊