Skip to content

Commit a755519

Browse files
authored
Merge pull request #353 from mohamedabdelhaq-123/add/for-vs-foreach-question
Add question about the difference between for loop and forEach
2 parents 6709151 + 429c181 commit a755519

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10918,6 +10918,59 @@ Common use cases and benefits:
1091810918
**[⬆ Back to Top](#table-of-contents)**
1091910919

1092010920

10921+
479. ### What is the difference between for loop and forEach
10922+
10923+
Both are used to iterate over arrays, but they differ in performance, flexibility, and purpose.
10924+
10925+
The `for` loop is a core JavaScript statement that gives you full control over iteration:
10926+
```javascript
10927+
const arr = [1, 2, 3];
10928+
for (let i = 0; i < arr.length; i++) {
10929+
console.log(arr[i]);
10930+
}
10931+
```
10932+
10933+
The `forEach` is an array method introduced in ES5 that accepts a callback and calls it for each element:
10934+
10935+
```javascript
10936+
const arr = [1, 2, 3];
10937+
arr.forEach((num) => console.log(num));
10938+
```
10939+
10940+
**Why is `for` loop faster?**
10941+
10942+
`forEach` has two sources of overhead on every iteration: first, it
10943+
invokes your callback using `.call()` (a function call has a cost).
10944+
Second, it checks for empty slots in the array (`i in this`) on every
10945+
single iteration even when the array has no empty slots at all. The
10946+
`for` loop does neither of these things, and JavaScript engines like
10947+
V8 are highly optimized for its simple counter pattern.
10948+
10949+
**Why was `forEach` created?**
10950+
10951+
For readability. The classic `for (let i = 0; i < arr.length; i++)`
10952+
is noisy you have to declare a counter, write a condition, and
10953+
increment manually, just to access each element. `forEach` hides all
10954+
of that mechanics and lets you focus on the element itself. Arrow
10955+
functions later made it even cleaner. However, they also made its
10956+
optional `thisArg` parameter (used to set `this` inside the callback)
10957+
mostly obsolete, since arrow functions inherit `this` automatically.
10958+
10959+
**When to use which:**
10960+
```javascript
10961+
// Use forEach — simple iterations where readability matters
10962+
arr.forEach((num) => console.log(num));
10963+
10964+
// Use for loop — when you need break, continue, or max performance
10965+
for (let i = 0; i < arr.length; i++) {
10966+
if (arr[i] === target) break; // impossible with forEach
10967+
}
10968+
```
10969+
10970+
**Note:** The `for` loop is strictly more powerful anything `forEach` does, `for` loop can do too, but not the other way around.
10971+
10972+
**[⬆ Back to Top](#table-of-contents)**
10973+
1092110974
<!-- QUESTIONS_END -->
1092210975
### Coding Exercise
1092310976

0 commit comments

Comments
 (0)