Junior
What is the fundamental difference between for and foreach loops?
sobes.tech AI
Answer from AI
for — a loop with a counter, allowing iteration over a numeric range or array indices. foreach (or for...of in JavaScript) is designed for iterating directly over elements of iterable objects (arrays, strings, Map, Set), without the need to work with indices. The main difference is in the way elements are accessed: for operates with indices, foreach — with values.
For:
// Example of for with an array
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // Access by index
}
Foreach (for...of):
// Example of for...of with an array
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item); // Access to the element's value
}
// Example of for...of with a string
const str = "abc";
for (const char of str) {
console.log(char); // Access to the character
}
Key differences:
| Characteristic | for | foreach (for...of) |
|---|---|---|
| Iteration method | By indices or numeric range | By values of the iterable object |
| Access to elements | Through index (arr[i]) |
Directly (const item of arr) |
| Ability to skip iterations | Yes (with continue) |
Yes (with continue) |
| Ability to break | Yes (with break) |
Yes (with break) |
| Applicability | General loop, suitable for any task | For iterable objects |
| Access to index | Available | Not (must be obtained additionally) |