Js Array Iteration in JavaScript
? JavaScript Array Iteration
Common Ways to Iterate Over Arrays in JavaScript
1. for Loop (Classic)
const arr = [10, 20, 30];for (let i = 0; i < arr.length; i++) { console.log(arr[i]);}2. for...of Loop (ES6+)
for (const value of arr) { console.log(value);}Cleaner syntax for iterating over iterable objects (like arrays).
3. forEach() Method
arr.forEach(function(value, index) { console.log(index, value);});// Using arrow functionarr.forEach((value, index) => { console.log(index, value);});Takes a callback executed once per element.
Cannot be broken early (no
break).
4. map() Method
const doubled = arr.map(value => value * 2);console.log(doubled); // [20, 40, 60]Returns a new array by applying a function to each element.
5. for...in Loop (Not Recommended for Arrays)
for (const index in arr) { console.log(index, arr[index]);}Iterates over keys (indexes), but also over inherited enumerable properties.
Generally, avoid for arrays; prefer
for,for...of, orforEach.
Summary Table
| Method | Description | Breakable? | Returns New Array? |
|---|---|---|---|
for loop | Classic index-based loop | Yes | No |
for...of | Loop over values | Yes (with break) | No |
forEach() | Callback per element | No | No |
map() | Transform each element | No | Yes |
for...in | Loop over keys (not recommended for arrays) | Yes | No |
Example: Print Each Element
const fruits = ["apple", "banana", "cherry"];// Using forEachfruits.forEach((fruit, i) => { console.log(i + ": " + fruit);});Need examples on filtering, reducing, or finding elements in arrays?