Back to Java
2026-01-035 min read

JS Array Iterations

Learn JS Array Iterations step by step with clear examples and exercises.

Why This Matters

Learning how to traverse and manipulate arrays in JavaScript is crucial as it forms the foundation for working with data structures in the language. Array methods such as forEach, map, filter, and reduce are widely used in real-world programming, including web development, data analysis, and algorithmic challenges. Mastering these techniques can help you write more efficient code and solve complex problems.

Prerequisites

Before diving into array iterations, make sure you have a good understanding of the following topics:

  1. Basic JavaScript syntax and variables
  2. Data structures in JavaScript (arrays and objects)
  3. Control flow statements (if-else, loops, etc.)
  4. Functions and function declarations
  5. Understanding of ES6 features like arrow functions, template literals, and destructuring assignments

Core Concept

Array Iteration Methods

JavaScript provides several built-in methods for iterating through arrays:

  1. forEach - Executes a provided function once for each element in the array. It does not return any value, but it can be used to perform side effects like logging or updating another data structure.
  2. map - Creates a new array with the results of calling a provided function on every element in the original array. The function passed to map should return a value that will be included in the resulting array.
  3. filter - Creates a new array with all elements that pass the test implemented by the provided function. The function passed to filter should return a boolean indicating whether an element should be included in the resulting array.
  4. reduce - Reduces the array to a single value by iteratively applying a function to each element and accumulating the result. The function passed to reduce takes two arguments: an accumulator (which holds the current intermediate value) and the current element being processed.

Using Array Iteration Methods

Here's an example demonstrating how to use these methods:

const numbers = [1, 2, 3, 4, 5];

// ForEach
numbers.forEach(number => {
console.log(number);
});

// Map
const squares = numbers.map(number => number * number);
console.log(squares); // [4, 9, 16, 25, 36]

// Filter
const evens = numbers.filter(number => number % 2 === 0);
console.log(evens); // [2, 4]

// Reduce
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15

Worked Example

Let's create a simple application that calculates the average of an array of numbers using forEach, map, and reduce.

const numbers = [1, 2, 3, 4, 5];

// ForEach
let total = 0;
numbers.forEach(number => {
total += number;
});
console.log(`Average (for-each): ${total / numbers.length}`);

// Map and Reduce
const squares = numbers.map(number => number * number);
const sumOfSquares = squares.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(`Average (map-reduce): ${Math.sqrt(sumOfSquares / numbers.length)}`);

Common Mistakes

  1. Forgetting to initialize the total variable before using it in a forEach loop. This can lead to unexpected results or errors when trying to perform calculations.
  2. Not returning the correct value from a function passed to map, filter, or reduce. If the function does not return a value, the resulting array or value will be incorrect.
  3. Incorrectly implementing the callback function for filter and reduce. The callback function should always return a boolean for filter and a value (or an updated accumulator) for reduce.
  4. Using forEach when a more concise method like map, filter, or reduce would be more appropriate. While forEach is useful for performing side effects, using it to create new arrays or calculate values can lead to less readable and less efficient code.

Common Mistakes (Sub-Expansion)

Incorrect Usage of Callback Functions

When implementing callback functions for filter and reduce, make sure they return the correct type:

  1. For filter, always return a boolean indicating whether an element should be included in the resulting array.
  2. For reduce, always return an updated accumulator or a final result.

Using Inappropriate Methods for Specific Tasks

While forEach is useful for performing side effects, it may not be the best choice when creating new arrays or calculating values. In such cases, consider using more concise methods like map, filter, and reduce.

Practice Questions

  1. Write a JavaScript function that finds all numbers greater than 10 in an array using the filter method.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const result = numbers.filter(number => number > 10);
console.log(result); // [11, 12, 13, 14, 15]
  1. Implement a function that calculates the product of all elements in an array using the reduce method.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.reduce((product, number) => product * number, 1);
console.log(result); // 120
  1. Given an array of objects, write a function that returns the average age of people using the map, reduce, and forEach methods.
const people = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 40 }
];

let totalAge = 0;
people.forEach(person => totalAge += person.age);
console.log(`Average (for-each): ${totalAge / people.length}`);

// Map and Reduce
const ages = people.map(person => person.age);
const result = ages.reduce((sum, age) => sum + age, 0);
console.log(`Average (map-reduce): ${result / people.length}`);

FAQ

Why should I use forEach, map, filter, and reduce in JavaScript?

These methods are essential for working with arrays in JavaScript, as they provide concise ways to iterate through arrays, perform calculations, and create new arrays based on specific conditions.

What is the difference between forEach and map in JavaScript?

While both methods iterate through arrays, forEach does not return a new array and is used for performing side effects like logging or updating another data structure, whereas map creates a new array with the results of calling a provided function on every element in the original array.

What is the purpose of the callback function in filter and reduce?

The callback function in both methods takes an element from the array as input and returns a value or a boolean, which determines whether the element should be included in the resulting array (in case of filter) or contributes to the accumulator (in case of reduce).

Why is it important to initialize the total variable before using it in a forEach loop?

Initializing the total variable ensures that it has a defined value before being used in calculations, preventing unexpected results or errors when trying to perform calculations on an empty array.

JS Array Iterations | Java | XQA Learn