Back to JavaScript
2026-01-097 min read

Exampl: Iterating over an array (JavaScript)

Learn Exampl: Iterating over an array (JavaScript) step by step with clear examples and exercises.

Why This Matters

Iterating over arrays is a fundamental concept in programming that allows us to traverse through each element in an array and perform operations on them. In this lesson, we will delve deeper into the importance of iterating over arrays in JavaScript, providing practical examples, common mistakes, and practice questions to help you master the technique.

Importance of Iterating Over Arrays

Iterating over arrays is essential for various programming tasks such as:

  • Calculating sums or averages of array elements
  • Finding specific values within an array
  • Updating or modifying array elements
  • Looping through arrays in functions and algorithms

Understanding how to iterate over arrays will help you solve real-world problems, prepare for interviews, and debug common issues that arise when working with arrays.

Prerequisites

Before diving into iterating over an array, you should have a basic understanding of the following concepts:

  1. JavaScript variables and data types
  2. Arrays in JavaScript (declaration, accessing elements)
  3. Basic control flow (if statements, for loops)
  4. Functions in JavaScript (definition, invocation, parameters, return values)
  5. ES6 syntax (let, const, arrow functions, template literals)

Core Concept

There are three main ways to iterate over an array in JavaScript:

  1. For Loop
  2. For...of Loop
  3. Array Methods (forEach, map, filter, reduce)
  4. While Loop (optional, for advanced users)

For Loop

The most common way to iterate over an array is by using a for loop. Here's the basic structure of a for loop that iterates over an array:

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

In this example, we initialize an array arr, set a counter variable i to 0, and loop through the array as long as i is less than the length of the array (arr.length). We can access each element using the index arr[i].

For...of Loop

The for...of loop is a more modern way to iterate over arrays in JavaScript. It provides an easier and more readable syntax compared to the for loop:

let arr = [1, 2, 3, 4, 5];
for (let value of arr) {
console.log(`Value: ${value}`);
}

In this example, we can see that the for...of loop automatically sets the counter variable value to each element in the array, making it easier to read and write.

Array Methods

Array methods are powerful tools that allow us to perform various operations on arrays with a single line of code. Some common array methods include:

  • forEach: Iterates over an array and executes a provided function once for each element
  • 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 provided by a function
  • reduce: Reduces an array to a single value by repeatedly applying a function to the current and next elements
  • some: Checks if at least one element in the array passes a test provided by a function
  • every: Checks if all elements in the array pass a test provided by a function
  • find: Returns 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

Here's an example using the forEach method:

let arr = [1, 2, 3, 4, 5];
arr.forEach(function(value) {
console.log(`Value: ${value}`);
});

In this example, we use the forEach method to iterate over the array and print each element to the console.

While Loop (Optional)

While loops are less commonly used for iterating over arrays compared to for loops and for...of loops. However, they can be useful in certain situations, such as when you don't know the exact length of an array or need more control over the loop conditions. Here's a basic example:

let arr = [1, 2, 3, 4, 5];
let i = 0;
while (i < arr.length) {
console.log(`Element at index ${i}: ${arr[i]}`);
i++;
}

In this example, we initialize an array arr, set a counter variable i to 0, and loop through the array as long as i is less than the length of the array (arr.length). We can access each element using the index arr[i].

Worked Example

Let's create a function that calculates the sum of all numbers in an array using a for loop, for...of loop, and the reduce method:

function calculateSum(arr) {
let total = 0;

// For Loop
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
console.log("For Loop: ", total);

// For...of Loop
let sum = 0;
for (let value of arr) {
sum += value;
}
console.log("For...of Loop: ", sum);

// Reduce Method
let result = arr.reduce((acc, val) => acc + val, 0);
console.log("Reduce Method: ", result);
}

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

In this example, we define a function calculateSum that takes an array as an argument and calculates the sum of its elements using three different methods: for loop, for...of loop, and reduce method. We then create an array arr, call the calculateSum function with the array as an argument, and print the results to the console.

Common Mistakes

  1. Forgetting to initialize the counter variable: In a for loop, it's essential to initialize the counter variable before starting the loop. If you forget to do so, JavaScript will throw an error.
  1. Incorrect array length: When using a for loop, make sure to use arr.length as the condition in the loop, not just length. If you're working with an object that has properties with numeric keys but isn't technically an array (e.g., JavaScript objects), you should check if the object is an array before using its length property.
  1. Iterating over arrays containing non-numeric values: When using a for loop or for...of loop, JavaScript will throw an error if the array contains non-numeric values (e.g., strings or objects). To avoid this issue, you can use the every method to check if all elements in the array are numbers before iterating over it.
  1. Misunderstanding the reduce method: The reduce method requires a function that takes two arguments: an accumulator (a value that stores the current result) and the current element of the array. Make sure you understand how to use the reduce method correctly to avoid common mistakes.

Practice Questions

  1. Write a for loop that prints all even numbers in the array [1, 2, 3, 4, 5].
  2. Using the map and filter methods, create a new array containing only the odd numbers from the array [1, 2, 3, 4, 5].
  3. Write a function that calculates the product of all numbers in an array using the reduce method.
  4. Implement a while loop to iterate over the array [1, 2, 3, 4, 5] and print each element.

FAQ

Q: What happens if I try to iterate over an object with a for loop or for...of loop?

A: If you attempt to iterate over an object (not an array) with a for loop or for...of loop, JavaScript will throw an error because objects don't have a length property. To avoid this issue, you can use the Object.keys() method to get an array of the object's keys and then iterate over that array instead.

Q: Can I use a for loop or for...of loop to iterate over strings?

A: Yes, you can use both for loops and for...of loops to iterate over strings in JavaScript. Strings are essentially arrays of characters, so you can treat them as such when iterating.

Q: How do I know which method to use when iterating over an array—for loop, for...of loop, or array methods?

A: The choice between using a for loop, for...of loop, or array methods depends on the specific task at hand and personal preference. For simple tasks like printing all elements in an array, either for loop or for...of loop can be used. For more complex operations, such as filtering, mapping, or reducing arrays, it's recommended to use array methods for readability and conciseness.

Q: What is the difference between forEach, map, and reduce array methods?

A: The forEach method iterates over an array and executes a provided function once for each element. It does not return a new array. The map method creates a new array with the results of calling a provided function on every element in the original array. The reduce method reduces an array to a single value by repeatedly applying a function to the current and next elements.

Q: How do I create an empty array?

A: In JavaScript, you can create an empty array using square brackets ([]) or the Array constructor (new Array()). For example:

let emptyArray = []; // Using square brackets
let anotherEmptyArray = new Array(); // Using the Array constructor
Exampl: Iterating over an array (JavaScript) | JavaScript | XQA Learn