Junior — Middle
Can you list and describe different types of for loops used in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, there are several types of for loops, each suitable for different tasks:
- Classic for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
Used when the range or number of iterations is known.
- for...in
const obj = {a: 1, b: 2};
for (let key in obj) {
console.log(key, obj[key]);
}
Iterates over the enumerable properties (keys) of an object. Not recommended for arrays, as it iterates over keys, not values.
- for...of
const arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
Iterates over iterable objects (arrays, strings, Map, Set, etc.), returning the values of elements.
- forEach (array method)
[1, 2, 3].forEach(item => console.log(item));
Although not a for loop in syntax, it is often used for iterating over arrays.
Each type of loop has its features and is used depending on the data structure and task.