JavaScript Array Iterations
JavaScript Array Iterations
Array iteration means going through each element of an array to perform an action. JavaScript provides multiple ways to iterate arrays.
1. for Loop
The traditional way to iterate:
Output:
2. for…of Loop
Modern loop to go through values of an array:
Output: Same as above
3. for…in Loop
Loops through indices (not recommended for arrays usually):
Output:
4. forEach() Method
Executes a callback function for each element:
Or using arrow function:
5. map() Method
Creates a new array by applying a function to each element:
6. filter() Method
Returns a new array containing elements that satisfy a condition:
7. reduce() Method
Used to reduce array to a single value:
8. some() & every() Methods
-
some()→ checks if at least one element satisfies a condition -
every()→ checks if all elements satisfy a condition
Summary Table
| Method/Loop | Use Case |
|---|---|
for |
Classic loop by index |
for...of |
Loop through values |
for...in |
Loop through indices |
forEach() |
Run function on each element |
map() |
Create new array from existing |
filter() |
Filter array based on condition |
reduce() |
Reduce array to single value |
some() |
Check if at least one matches |
every() |
Check if all match |
Example: Iterating Array
Output:
