Junior — Middle
What are the differences between for and for-in loops when iterating over elements in JavaScript?
sobes.tech AI
Answer from AI
The for loop in JavaScript is typically used for iterating over array elements by index and looks like:
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
The for-in loop is designed for iterating over enumerable properties of an object, including array indices as strings:
for (let key in object) {
console.log(key, object[key]);
}
Main differences:
foriterates over array elements by numeric indices from 0 to array length.for-initerates over object keys (including prototype properties ifhasOwnPropertyis not used), and for arrays, keys are strings with indices, which can lead to surprises.
For array iteration, it is recommended to use the classic for or for-of, while for-in is suitable for objects.