JavaScript Array Loops
Working with arrays inevitably means you need to read or manipulate the data inside them. JavaScript provides multiple ways to iterate (loop) over an array. Each method has its own specific use case.
The Classic for Loop
The original method for iteration. It gives you the highest level of control. You define an initial counter, the condition to stop, and how the counter increments. It is highly performant and allows you tobreak orcontinue out of the loop easily.
The for...of Loop
Introduced in ES6, for...ofis often the preferred loop when you just need the values. It hides the index management and prevents off-by-one errors. It is cleaner and highly readable.
The forEach() Method
forEach() is an Array method that expects a callback function. It runs that callback once for each item. It fits perfectly into a functional programming style. Note: You cannot use `break` or `continue` inside a `forEach`.
What about for...in?+
Avoid using `for...in` to iterate over an array. The `for...in` statement iterates over all enumerable properties of an object that are keyed by strings. While an array's indexes are technically object keys, `for...in` will return them as strings ("0", "1", "2") and might also iterate over custom properties added to the Array prototype. Stick to `for...of` or `forEach` for arrays.
