Javascript Loops Cheatsheet
I realized that understanding the nuances of loops is crucial for writing clean, efficient, and bug-free code. Whether you're working on a React app, processing data, or just iterating over an array, choosing the right loop can make a big difference.
As a developer, I’ve often found myself wondering:
- Which loop should I use here?
- Can I break or continue in this type of loop
- What’s the most efficient way to iterate over this data?
That’s why I decided to create this loop comparison and cheat sheet—to help myself and others quickly reference the best practices and use cases for each type of loop. If anything in the post wasn’t clear, or if you would like to add anything, feel free to drop your questions in the comments! I’d love to help clarify things or dive deeper into any topic.
Iterations Comparison Table
Iteration / Loop Type | Use Case | Can break/continue? |
---|---|---|
for...of |
Iterate over iterable objects (values). When you need the values, not the indices. | Yes |
for...in |
Iterate over object keys (or array indices) | Yes |
do...while |
Run at least once, then continue based on condition | Yes |
forEach |
Functional iteration over array elements | No |
map/filter/reduce |
Functional array operations (transform, filter, or reduce arrays | No |
while |
Indefinite iteration based on a condition | Yes |
for |
Definite iteration with counters or indices. When you need precise control over the loop | Yes |
Explanation of "Can break/continue?"
-
break
: This statement allows you to exit the loop prematurely. -
continue
: This statement allows you to skip the current iteration and move to the next one.
What iteration do I usually go with when creating a fullstack App?
-
for
,while
,do...while
:- Use these for low-level control, such as polling APIs, validating input, or iterating with indices.
-
for...of
:- Great for iterating over arrays or iterables when you need to break or continue.
-
for...in
:- Useful for iterating over object keys and I usually avoid using it for arrays.
-
forEach
:- Use for simple iteration over arrays when you don't need to break or continue.
-
map
,filter
,reduce
:- Use these for transforming, filtering, or reducing arrays in a functional way. They are commonly used in React for rendering lists or processing data.
EXAMPLES
1. for...of
Loop
- Iterates over iterable objects such as arrays, strings, sets, maps, etc.
- Accesses the value directly (not the index).
Example:
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit); // Output: apple, banana, cherry
}
When to use:
- When you only care about the values and not the indices.
- For iterating over iterable objects like arrays, strings, or sets.
2. for...in
Loop
- Iterates over the keys (or properties) of an object.
- Also works with arrays but iterates over the indices (not recommended for arrays).
Example with Object:
const person = { name: 'John', age: 30, city: 'New York' };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: John
// age: 30
// city: New York
Example with Array (not recommended):
const fruits = ['apple', 'banana', 'cherry'];
for (const index in fruits) {
console.log(index, fruits[index]);
}
// Output:
// 0 apple
// 1 banana
// 2 cherry
When to use:
- For iterating over properties of an object.
- Avoid for arrays because it iterates over enumerable properties, which might include unexpected properties.
3. do...while
Loop
- Similar to a
while
loop but guarantees at least one execution because the condition is checked after the loop runs.
Example:
let count = 0;
do {
console.log(count);
count++;
} while (count < 3);
// Output: 0, 1, 2
When to use:
- When you need the loop to run at least once, regardless of the condition.
4. forEach
(Array Method)
- A method provided by arrays that executes a function for each element in the array.
Example:
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// Output:
// 0: apple
// 1: banana
// 2: cherry
When to use:
- When working specifically with arrays and you want concise, functional-style iteration.
- If you need to stop iteration early, you can throw an exception (not recommended) or use a traditional loop.
5. map
, filter
, and reduce
(Array Methods)
These methods aren't traditional loops but are used for iterating over arrays in functional programming.
-
Functional Methods (
map
,filter
,reduce
):- These methods are designed for immutability and functional programming paradigms, so they don't support breaking or continuing. Instead, you can chain methods or use
filter
to exclude elements.
- These methods are designed for immutability and functional programming paradigms, so they don't support breaking or continuing. Instead, you can chain methods or use
map
Example:
Transforms each element and creates a new array.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
filter
Example:
Filters elements based on a condition.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]
reduce
Example:
Reduces the array to a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 10
When to use:
- When you want to transform, filter, or aggregate arrays in a more declarative and functional style.
6. while
Loop
- Executes a block of code as long as a specified condition is true.
- The condition is checked before each iteration.
Example:
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
// Output: 0, 1, 2
When to use:
- When you don't know how many iterations you need in advance.
- When the loop continuation depends on a condition that might change during execution.
7. for
Loop
- The most traditional and versatile loop in JavaScript.
- Consists of an initializer, condition, and increment/decrement expression.
Example:
for (let i = 0; i < 3; i++) {
console.log(i);
}
// Output: 0, 1, 2
When to use:
- When you need precise control over the iteration process.
- When you need to iterate a specific number of times.
- When you need access to the counter variable.
If anything in the post wasn’t clear, or if you would like to add anything, feel free to drop your questions in the comments! I’d love to help clarify things or dive deeper into any topic.
Let’s learn and grow together! 💡