Last active
October 30, 2025 05:55
-
-
Save Dev-Dipesh/48fcdefa69836b3310dd5d1949a7fbb6 to your computer and use it in GitHub Desktop.
Javascript loops can be quite confusing. Knowing the write loop to use can make a big difference in performance.
| Loop Type | Description | Use Case | Limitations/Constraints |
|---|---|---|---|
for |
Traditional loop with initialization, condition, and increment. | When you need precise control over the loop (e.g., non-standard increments, specific ranges). | Requires manual handling of the loop variable and condition. |
forEach |
Executes a function for each item in an array. | To perform operations on each array item without modifying the array. Cannot break early. | Cannot break out of the loop or return a value from the array loop. |
map |
Transforms each element in an array and returns a new array of equal length. | When you need to transform elements in an array and use the transformed array. | Only for transformations; not suitable for non-returning operations. |
while |
Repeats a block of code as long as the condition is true. | When the number of iterations is not known in advance but determined by a condition. | Easy to cause infinite loops if the condition is not managed carefully. |
do...while |
Executes code block once before checking condition and repeating loop. | When the loop must execute at least once and the condition is checked after the first run. | Like while, but ensures at least one iteration. |
for...of |
Iterates over iterable objects, yielding the values directly. | Ideal for looping over elements of an iterable when you need the values, not the indices. | Not suitable for accessing object properties directly. |
for...in |
Iterates over enumerable properties of an object. | To iterate over object properties, but requires checking with hasOwnProperty for safety. |
Iterates over all enumerable properties, including inherited ones. |
for await...of |
Iterates over asynchronous iterables. | For handling asynchronous data like streams or in conjunction with async/await. | Requires the source to be an asynchronous iterable. |
-
forEach:- Since
forEachdoes not allow breaking out or returning midway, it may not be suitable for cases where you need to terminate early based on a condition.
- Since
-
map:- Being designed for transformation,
mapwill always return a new array, making it inefficient if you're not using the produced array.
- Being designed for transformation,
-
for...ofvsfor...in:for...ofis useful for arrays and other iterable types, focusing on the values.for...inis more tailored for objects where you need to access keys but must be cautious about inherited properties.
-
for await...of:- Very specific to scenarios involving asynchronous processing, such as consuming data from APIs in real-time or handling stream-based data.
-
forEachvsmap:- Use
forEachfor actions. - Use
mapfor creating new transformed arrays.
- Use
-
forvsfor...of:- Use
forfor detailed control over iteration. - Use
for...offor simpler syntax when accessing array elements directly.
- Use
-
whilevsdo...while:- Use
whilewhen the condition is checked before the first iteration. - Use
do...whilewhen at least one iteration is required before condition check.
- Use
-
for...inCaution:- It can loop through inherited properties, so it's less commonly used for arrays and more for object properties with proper checks.
// Iterates from 0 to 9
for (let i = 0; i < 10; i++) {
console.log(i);
}// Executes a function on each item in an array
['a', 'b', 'c'].forEach((element, index) => {
console.log(`${index}: ${element}`);
});// Returns a new array with each element doubled
const doubled = [1, 2, 3].map(num => num * 2);
console.log(doubled);// Continues until `x` becomes 0
let x = 5;
while (x > 0) {
console.log(x);
x--;
}// Executes at least once even if the condition is initially false
let y = 5;
do {
console.log(y);
y--;
} while (y > 5);// Iterates over array elements
for (let value of ['x', 'y', 'z']) {
console.log(value);
}// Iterates over the properties of an object
const obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(`${key}: ${obj[key]}`);
}
}// Example assuming `asyncIterable` is an asynchronous iterable
async function process() {
const asyncIterable = {
async *[Symbol.asyncIterator]() {
yield "hello";
yield "async";
yield "world";
}
};
for await (let value of asyncIterable) {
console.log(value);
}
}
process();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
