Array Traversal with Examples

Learn Array Traversal with Examples with practical examples, explanations, best practices, and real-world coding techniques.

What Is Array Traversal?

Array traversal is the process of visiting each element in an array, usually one at a time, so that the elements can be read, processed, compared, or transformed. Traversal is one of the most basic and frequently used operations in data structures.

For example, if an application stores the scores of several students in an array, traversal can be used to display every score, calculate the total, find the highest score, or count values that satisfy a condition.

const scores = [85, 92, 78, 96, 88];

for (let i = 0; i < scores.length; i++) {
  console.log(scores[i]);
}

The loop starts at index 0 and continues until the last valid index. Every element is visited exactly once.

Why Array Traversal Is Important

Many array-based algorithms begin with traversal. Before an application can analyze or modify a collection, it often needs to examine its elements.

  • Display all elements in a collection.
  • Calculate totals or averages.
  • Find the minimum or maximum value.
  • Search for a particular element.
  • Count elements that satisfy a condition.
  • Modify selected elements.
  • Build another collection from existing data.

Forward Traversal Using an Index

The traditional way to traverse an array is to use an indexed for loop. This approach gives you direct access to both the index and the element.

const languages = ['JavaScript', 'Python', 'Java', 'C#'];

for (let i = 0; i < languages.length; i++) {
  console.log(languages[i]);
}

This method is particularly useful when the index is needed for another calculation or when elements must be updated during traversal.

Traversing with Index and Value

Because the loop variable represents the index, you can use it to display the position of every element along with its value.

const fruits = ['Apple', 'Banana', 'Orange'];

for (let i = 0; i < fruits.length; i++) {
  console.log('Index:', i, 'Value:', fruits[i]);
}

Traversal Using for...of

JavaScript's for...of loop provides a convenient way to traverse the values of an array when the index is not required.

const numbers = [10, 20, 30, 40];

for (const number of numbers) {
  console.log(number);
}

This approach is often easier to read when the task only requires processing each value.

Reverse Array Traversal

An array can also be traversed from the last element toward the first. A reverse traversal starts at length - 1 and decreases the index until it reaches zero.

const numbers = [10, 20, 30, 40];

for (let i = numbers.length - 1; i >= 0; i--) {
  console.log(numbers[i]);
}

Reverse traversal is useful when processing the newest elements first, reading a collection backward, or solving problems that require right-to-left processing.

Traversing with a Condition

Traversal can be combined with conditions to process only elements that satisfy a particular requirement.

const numbers = [12, 7, 18, 5, 24, 9];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    console.log(numbers[i]);
  }
}

This example visits every element but prints only the even values.

Calculating a Sum During Traversal

A common traversal pattern is maintaining an accumulator while visiting each element. For example, a sum can be calculated by adding each value to a running total.

const prices = [100, 250, 75, 125];

let total = 0;

for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}

console.log(total); // 550

The algorithm visits each element once, so its time complexity is O(n).

Finding the Maximum Value

Traversal can also be used to find the largest value in an array. The algorithm keeps track of the largest value found so far and updates it whenever a larger element is encountered.

const numbers = [42, 17, 89, 35, 64];

let maximum = numbers[0];

for (let i = 1; i < numbers.length; i++) {
  if (numbers[i] > maximum) {
    maximum = numbers[i];
  }
}

console.log(maximum); // 89

The same traversal pattern can be adapted to find the minimum value.

Updating Elements During Traversal

When the index is available, traversal can be used to modify elements in the original array. For example, every value can be increased by a fixed amount.

const prices = [100, 200, 300];

for (let i = 0; i < prices.length; i++) {
  prices[i] += 10;
}

console.log(prices);
// [110, 210, 310]

Using the index is important here because assigning to the loop variable itself would not modify the original array.

Counting Elements During Traversal

Another common pattern is counting how many elements satisfy a condition.

const scores = [85, 42, 91, 67, 38, 74];

let passed = 0;

for (const score of scores) {
  if (score >= 50) {
    passed++;
  }
}

console.log(passed); // 4

Traversal with forEach()

JavaScript also provides the forEach() method for executing a function once for every array element.

const languages = ['JavaScript', 'Python', 'Java'];

languages.forEach((language, index) => {
  console.log(index, language);
});

The callback receives the current value, its index, and the array itself. This makes forEach() useful when you want concise iteration without manually managing the loop counter.

Nested Array Traversal

When an array contains other arrays, traversal can be performed at multiple levels. This pattern is common when working with matrices and two-dimensional data.

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

for (let row = 0; row < matrix.length; row++) {
  for (let column = 0; column < matrix[row].length; column++) {
    console.log(matrix[row][column]);
  }
}

If a matrix contains r rows and c columns, visiting every element takes O(r × c) time.

Traversal Patterns Used in Problem Solving

Array traversal is often the foundation of more advanced algorithms. A problem may require simple iteration or combine traversal with additional state such as a counter, running sum, previous value, or lookup structure.

Pattern Typical Use
Forward traversal Process elements from left to right
Reverse traversal Process elements from right to left
Conditional traversal Process selected elements
Accumulator Calculate totals, products, or other aggregates
Tracking best value Find minimum or maximum values
Nested traversal Process matrices or nested collections

Array Traversal Complexity

Traversing an array requires visiting its elements. Therefore, if an array contains n elements, a complete traversal takes O(n) time.

Traversal Type Time Complexity Extra Space
Forward traversal O(n) O(1)
Reverse traversal O(n) O(1)
for...of traversal O(n) O(1)
Nested traversal O(r × c) O(1), excluding input

Common Mistakes

  • Starting an array loop at index 1 instead of index 0 when the first element must be processed.
  • Using i <= array.length, which attempts to access an invalid index.
  • Forgetting to decrease the index during reverse traversal.
  • Modifying an array while traversing it without considering how the indexes change.
  • Using nested loops unnecessarily when a single traversal is sufficient.
  • Confusing a copied array with the original array when performing transformations.

Key Takeaways

  • Array traversal means visiting array elements one by one.
  • Forward traversal normally starts at index 0 and moves toward the last index.
  • Reverse traversal starts at the last index and moves toward index 0.
  • for, for...of, and forEach() are common JavaScript traversal techniques.
  • Traversal is commonly combined with searching, counting, aggregation, and conditional processing.
  • A complete traversal of n elements takes O(n) time.
  • Array traversal is a fundamental pattern behind many coding and algorithm problems.

Code Examples

const numbers = [10, 20, 30, 40, 50];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
    
const numbers = [10, 20, 30, 40, 50];

for (let i = numbers.length - 1; i >= 0; i--) {
  console.log(numbers[i]);
}
    
const numbers = [42, 17, 89, 35, 64];

let maximum = numbers[0];

for (let i = 1; i < numbers.length; i++) {
  if (numbers[i] > maximum) {
    maximum = numbers[i];
  }
}

console.log('Maximum:', maximum); // 89
    
const numbers = [12, 7, 18, 5, 24, 9];

for (const number of numbers) {
  if (number % 2 === 0) {
    console.log(number);
  }
}
    

Pro Tip

Before writing an array loop, identify exactly what the traversal needs to accomplish. If you need the index, use an indexed loop; if you only need each value, for...of is often clearer. For algorithm problems, also check whether the traversal can be combined with other work in a single pass.

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.