How to Iterate Over an Array in JavaScript: Top Mistakes and How to Avoid Them
\n\nHave you ever written code that was supposed to simply go through a to-do list or items in a shopping cart, but instead returned undefined, an infinite loop, or, even worse, silently corrupted data? A familiar pain. The question "How to loop through the items of an array in JavaScript?" is one of the most popular on Stack Overflow. It seems like it couldn't be simpler, right? But the devil, as always, is in the details.
Today, we won't just break down how to iterate over an array in JavaScript. We'll look under the hood of the most common pitfalls that beginners (and not only) stumble into. You'll learn why for...in can let you down, how forEach differs from map, and how to avoid an infinite loop in for.
Ready? Let's go fix bugs and write clean code.
\n\nMistake #1: Using for...in for Arrays
\n\nThis is perhaps the most insidious beginner mistake. A developer sees the word for and the word in and thinks: "Oh, this is for iterating over everything!" Technically, that's true. But for arrays, it's a disaster.
The for...in loop is designed to iterate over an object's properties, not array elements. Yes, an array in JS is also an object, but its indices are just string keys ("0", "1", "2").
Here's the catch:
\n- \n
- Order is not guaranteed. Although browsers usually maintain order, you cannot rely on it. \n
- It iterates over the entire prototype chain. If you or some library added a method to
Array.prototype(e.g.,Array.prototype.myCustomMethod = function() {}),for...inwill pick it up too. \n
Code Example (How NOT to do it):
\nconst arr = [10, 20, 30];\nArray.prototype.customMethod = () => {};\n\nfor (let index in arr) {\n console.log(arr[index]); // Outputs: 10, 20, 30, ƒ () => {}\n}\n\n\nSee? Our custom function popped up at the end. The code broke.
\n\nHow to do it correctly:
\nUse for...of (for values) or the classic for (for indices). for...of iterates only over values and ignores the prototype.
// Correct and safe\nfor (let value of arr) {\n console.log(value); // 10, 20, 30\n}\n\n\nMistake #2: Forgetting About the Callback in forEach
\n\narr.forEach(callback) is an elegant way to iterate over an array in JavaScript. But many confuse it with map or filter. The main mistake is thinking that forEach returns something. It returns undefined.
A second common mistake is forgetting about the second and third arguments of the callback (the index and the array itself). Sometimes this is critical.
\n\nExample of the mistake:
\nconst numbers = [1, 2, 3];\nconst doubled = numbers.forEach(num => num * 2);\nconsole.log(doubled); // undefined! Mistake.\n\n\nHow to do it correctly:
\nIf you need to create a new array based on an old one — use map(). If you only need to perform an action (e.g., log to the console or send data) — use forEach().
// For creating a new array\nconst doubled = numbers.map(num => num * 2); // [2, 4, 6]\n\n// For side effects\nnumbers.forEach((num, index) => {\n console.log(`Element ${index}: ${num}`);\n});\n\n\nMistake #3: Infinite Loop in for
\n\nA classic. You write for (let i = 0; i < arr.length; i++), but forget the increment i++ or, even worse, modify the array inside the loop.
Let's say you filter an array on the fly, removing elements with splice(). If you don't corre