Back to JavaScript
2026-01-158 min read

JS Array Iterations (JavaScript)

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

Why This Matters

In this comprehensive lesson on JavaScript Array Iterations, we will explore various methods for traversing and manipulating arrays in JavaScript. Understanding these techniques is crucial for any developer, as it enables efficient data management, problem-solving, and code optimization. By mastering array iterations, you can write cleaner, more maintainable code, prepare for interviews, and debug issues in production environments.

Prerequisites

To fully grasp the concepts presented in this lesson, you should be comfortable with:

  1. Basic JavaScript syntax, including variables, data types, operators, and control structures (if, else, switch).
  2. Creating and accessing array elements using array literals and index numbers.
  3. Understanding the fundamental concepts of object-oriented programming in JavaScript, such as methods and properties.
  4. Familiarity with ES6 syntax and features like arrow functions, template literals, and destructuring assignments is beneficial but not required.

Core Concept

JavaScript offers several ways to iterate through arrays:

  1. for loop: a traditional loop that allows you to explicitly control the iteration process.
  2. forEach(): an array method that executes a provided function once for each element in the array.
  3. map(), filter(), reduce(): higher-order functions that let you transform, filter, and combine arrays, respectively.
  4. every() and some(): methods to test whether all or at least one elements in an array meet a certain condition.
  5. find() and findIndex(): methods to search for the first element in an array that satisfies a provided testing function.
  6. forEachReverse(): an extension method to iterate through arrays in reverse order (not natively supported in JavaScript).

for loop

The for loop is the most basic iteration construct in JavaScript. It consists of an initialization, a condition, and an increment (or decrement) expression. Here's how to use it with arrays:

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

forEach()

The forEach() method is a built-in array function that executes a provided callback function once for each element in the array. It's more concise than a traditional for loop and can help make your code cleaner and easier to read.

let arr = [1, 2, 3, 4, 5];
arr.forEach(function(element) {
console.log(element);
});

map(), filter(), reduce()

The map(), filter(), and reduce() methods are higher-order functions that help you manipulate arrays in various ways:

  1. map() creates a new array with the results of calling a provided function on every element in the original array.
  2. filter() creates a new array with all elements that pass a test implemented by the provided function.
  3. reduce() applies a function against an accumulator and each element in the array, reducing it to a single output value.

Here's an example using these functions:

let arr = [1, 2, 3, 4, 5];

// map() example
let squares = arr.map(function(element) {
return element * element;
});
console.log(squares); // [1, 4, 9, 16, 25]

// filter() example
let evens = arr.filter(function(element) {
return element % 2 === 0;
});
console.log(evens); // [2, 4]

// reduce() example
let sum = arr.reduce(function(total, current) {
return total + current;
}, 0);
console.log(sum); // 15

every(), some(), find(), and findIndex()

The every(), some(), find(), and findIndex() methods help you search for specific conditions within an array:

  1. every() checks if all elements in the array meet a certain condition.
  2. some() checks if at least one element in the array meets a certain condition.
  3. find() searches for the first element in the array that satisfies a provided testing function.
  4. findIndex() returns the index of the first element in the array that satisfies a provided testing function.

Here's an example using these methods:

let arr = [1, 2, 3, 4, 5];

// every() example
console.log(arr.every(function(element) {
return element < 6; // false because one element (5) is greater than 6
}));

// some() example
console.log(arr.some(function(element) {
return element > 3; // true because at least one element (4 and 5) is greater than 3
}));

// find() example
let foundElement = arr.find(function(element) {
return element > 3; // returns the first element greater than 3, i.e., 4
});
console.log(foundElement);

// findIndex() example
let foundIndex = arr.findIndex(function(element) {
return element > 3; // returns the index of the first element greater than 3, i.e., 2
});
console.log(foundIndex);

forEachReverse() (extension method)

Although not natively supported in JavaScript, you can use extension methods like forEachReverse() to iterate through arrays in reverse order:

Array.prototype.forEachReverse = function(callback) {
for (let i = this.length - 1; i >= 0; i--) {
callback(this[i], i, this);
}
};

let arr = [1, 2, 3, 4, 5];
arr.forEachReverse(function(element) {
console.log(element);
});

Worked Example

Let's create a simple JavaScript application that calculates the average of an array of numbers using all six iteration methods: for, forEach, map, reduce, every, and some.

let arr = [1, 2, 3, 4, 5];

// for loop example
let totalFor = 0;
for (let i = 0; i < arr.length; i++) {
totalFor += arr[i];
}
console.log('Average using for loop:', totalFor / arr.length);

// forEach() example
let totalForEach = 0;
arr.forEach(function(element) {
totalForEach += element;
});
console.log('Average using forEach():', totalForEach / arr.length);

// map() example
let squares = arr.map(function(element) {
return element * element;
});
let totalMap = squares.reduce((total, current) => total + current, 0);
console.log('Average using map():', totalMap / squares.length);

// reduce() example
let totalReduce = arr.reduce(function(total, current) {
return total + current;
}, 0);
console.log('Average using reduce():', totalReduce / arr.length);

// every() example
console.log('All elements are less than 6:', arr.every(function(element) {
return element < 6; // true because all elements are less than 6
}));

// some() example
console.log('At least one element is greater than 3:', arr.some(function(element) {
return element > 3; // false because no element is greater than 3
}));

Common Mistakes

  1. Forgetting to initialize the accumulator variable in a for loop:
let arr = [1, 2, 3, 4, 5];
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i]; // correct
}
console.log(total); // 15
  1. Using forEach() when you need to access the index:
let arr = [1, 2, 3, 4, 5];
arr.forEach(function(element, index) {
console.log('Element:', element, 'Index:', index); // correct
});
  1. Incorrectly using map(), filter(), or reduce():
let arr = [1, 2, 3, 4, 5];
// map() example (incorrect)
let squaresWrong = arr.map(function(element) {
return element + element; // should be multiplication instead of addition
});
console.log(squaresWrong); // [2, 4, 6, 8, 10]
  1. Incorrectly using every() or some():
let arr = [1, 2, 3, 4, 5];
// every() example (incorrect)
console.log(arr.every(function(element) {
return element > 0; // true because all elements are greater than 0
})); // incorrect result: true instead of false

Practice Questions

  1. Write a JavaScript function that takes an array and returns the sum of all even numbers using forEach().
  2. Write a JavaScript function that removes duplicates from an array using filter().
  3. Write a JavaScript function that finds the maximum number in an array using reduce().
  4. Write a JavaScript function that reverses the order of elements in an array using forEachReverse() and a temporary storage array.
  5. Write a JavaScript function that calculates the average of an array using all six iteration methods (for, forEach, map, reduce, every, and some) and compares their performance.
  6. Implement the forEachReverse() extension method for arrays.
  7. Create a JavaScript function that finds the second-highest number in an array using sort() and filter().
  8. Write a JavaScript function that checks if an array contains any duplicates using every() or some().
  9. Implement a JavaScript function that sorts an array of objects by their property values using map(), sort(), and reduce().
  10. Create a JavaScript function that finds the kth smallest number in an array using the QuickSelect algorithm.

FAQ

  1. Why should I use forEach() instead of a traditional for loop?
  • forEach() is more concise, making your code cleaner and easier to read. It also avoids the need to manage an explicit index variable. However, it does not provide direct access to the array's index, so you may need to use additional methods like Array.prototype.indexOf() or a second argument in the callback function if required.
  1. What is the difference between map(), filter(), and reduce()?
  • map() creates a new array with the results of calling a provided function on every element in the original array.
  • filter() creates a new array with all elements that pass a test implemented by the provided function.
  • reduce() applies a function against an accumulator and each element in the array, reducing it to a single output value.
  1. Why is using forEach() instead of a traditional for loop not always recommended?
  • While forEach() can make your code cleaner, it does not allow you to access the index or directly manipulate the original array. If you need to perform operations that require these functionalities, a traditional for loop may be more appropriate.
  1. Why is using reduce() instead of a traditional for loop beneficial?
  • reduce() can help simplify complex algorithms by reducing multiple iterations into one concise function call. It also allows you to perform operations that require an accumulator, such as calculating the sum or product of all elements in an array.
  1. What is the difference between every(), some(), find(), and findIndex()?
  • every() checks if all elements in the array meet a certain condition.
  • some() checks if at least one element in the array meets a certain condition.
  • find() searches for the first element in the array that satisfies a provided testing function.
  • findIndex() returns the index of the first element in the array that satisfies a provided testing function.
  1. Why is using an extension method like forEachReverse() beneficial?
  • Extension methods can help you extend native JavaScript objects with new functionality, making it easier to work with arrays and other data structures in your code. Using forEachReverse(), for example, allows you to iterate through arrays in reverse order without writing a separate function for that purpose.
JS Array Iterations (JavaScript) | JavaScript | XQA Learn