Skip to content

Instantly share code, notes, and snippets.

@Dev-Dipesh
Last active May 10, 2024 07:10
Show Gist options
  • Save Dev-Dipesh/48fcdefa69836b3310dd5d1949a7fbb6 to your computer and use it in GitHub Desktop.
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.

A4 Image file if you would like to print it ♥ JS Loops Cheatsheet

Javascript Loops Cheatsheet

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.

Additional Notes

  • forEach:

    • Since forEach does not allow breaking out or returning midway, it may not be suitable for cases where you need to terminate early based on a condition.
  • map:

    • Being designed for transformation, map will always return a new array, making it inefficient if you're not using the produced array.
  • for...of vs for...in:

    • for...of is useful for arrays and other iterable types, focusing on the values.
    • for...in is 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.
  • forEach vs map:

    • Use forEach for actions.
    • Use map for creating new transformed arrays.
  • for vs for...of:

    • Use for for detailed control over iteration.
    • Use for...of for simpler syntax when accessing array elements directly.
  • while vs do...while:

    • Use while when the condition is checked before the first iteration.
    • Use do...while when at least one iteration is required before condition check.
  • for...in Caution:

    • It can loop through inherited properties, so it's less commonly used for arrays and more for object properties with proper checks.

1. for

// Iterates from 0 to 9
for (let i = 0; i < 10; i++) {
    console.log(i);
}

2. forEach

// Executes a function on each item in an array
['a', 'b', 'c'].forEach((element, index) => {
    console.log(`${index}: ${element}`);
});

3. map

// Returns a new array with each element doubled
const doubled = [1, 2, 3].map(num => num * 2);
console.log(doubled);

4. while

// Continues until `x` becomes 0
let x = 5;
while (x > 0) {
    console.log(x);
    x--;
}

5. do...while

// Executes at least once even if the condition is initially false
let y = 5;
do {
    console.log(y);
    y--;
} while (y > 5);

6. for...of

// Iterates over array elements
for (let value of ['x', 'y', 'z']) {
    console.log(value);
}

7. for...in

// 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]}`);
    }
}

8. for await...of

// 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