JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Array Iteration


Iterating over arrays is a core aspect of JavaScript programming. Arrays often hold multiple values, and performing operations on each element—such as displaying, modifying, or calculating results—requires iteration. JavaScript provides a variety of ways to iterate over arrays, each suited for different scenarios, from simple loops to higher-order functions.

This tutorial covers array iteration techniques, practical examples, best practices, and common mistakes.

Why Array Iteration Is Important

Array iteration is essential for:

  • Processing data from APIs, forms, or user inputs

  • Applying transformations to each element

  • Filtering, searching, and aggregating values

  • Building dynamic lists, tables, and content

  • Performing calculations on arrays of numbers or objects

Without iteration, working with arrays would be tedious and inefficient.

Common Array Iteration Methods

JavaScript offers several ways to loop through arrays, each with specific advantages.

for Loop

The classic for loop is straightforward and works in all scenarios:

let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

This method provides full control over the index and loop behavior.

for...of Loop

The for...of loop is modern and readable. It iterates directly over values:

for (let fruit of fruits) {
  console.log(fruit);
}

It’s ideal when you don’t need the index.

forEach()

forEach() is an array method that executes a callback function for each element:

fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

Advantages:

  • Cleaner syntax than for loops

  • Access to both value and index

  • Readable and expressive for functional-style programming

Note: forEach() does not return a new array.

map()

map() iterates over an array and returns a new array containing the results of the callback function:

let numbers = [1, 2, 3, 4];
let squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16]

map() is ideal for transforming data without mutating the original array.

filter()

filter() iterates and creates a new array with elements that pass a condition:

let scores = [45, 78, 90, 60];
let passingScores = scores.filter(score => score >= 60);
console.log(passingScores); // [78, 90, 60]

This is useful for extracting subsets of data.

reduce()

reduce() iterates over an array and reduces it to a single value, such as a sum or concatenated string:

let total = scores.reduce((sum, score) => sum + score, 0);
console.log(total); // 273

reduce() is powerful for cumulative calculations and aggregations.

some() and every()

Both methods iterate to check conditions:

  • some() returns true if at least one element satisfies the condition.

  • every() returns true only if all elements satisfy the condition.

console.log(scores.some(score => score > 90)); // false
console.log(scores.every(score => score >= 45)); // true

for...in Loop

for...in iterates over property names. While it can be used for arrays, it’s not recommended because it includes inherited properties and is intended for objects.

for (let index in fruits) {
  console.log(fruits[index]);
}

Practical Examples

Example 1: Displaying a List of Names

let students = ["Emma", "Lily", "Sophia"];
students.forEach((student, index) => {
  console.log(`Student ${index + 1}: ${student}`);
});

Example 2: Calculating Squares

let numbers = [2, 4, 6, 8];
let squared = numbers.map(n => n * n);
console.log(squared); // [4, 16, 36, 64]

Example 3: Filtering Adults

let ages = [12, 17, 19, 25];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [19, 25]

Example 4: Summing Values

let prices = [50, 100, 25, 75];
let totalPrice = prices.reduce((sum, price) => sum + price, 0);
console.log(`Total: ${totalPrice}`); // Total: 250

Example 5: Checking Conditions

let numbers = [1, 2, 3, 4, 5];
console.log(numbers.some(num => num > 4)); // true
console.log(numbers.every(num => num < 10)); // true

Example 6: Iterating with for...of

for (let name of students) {
  console.log(`Hello, ${name}!`);
}

Common Mistakes

  • Using for...in for arrays and unintentionally iterating over inherited properties.

  • Expecting forEach() to return a new array; it does not.

  • Forgetting that map(), filter(), and reduce() return new arrays or values and do not modify the original array unless reassigned.

  • Overusing loops when array methods could provide cleaner, more functional solutions.

Best Practices

  • Use for...of or forEach() for readable iteration over values.

  • Use map(), filter(), and reduce() for transformations and calculations.

  • Avoid for...in for arrays; stick to loops or array methods.

  • Keep callback functions concise and use arrow functions for readability.

  • Be mindful of whether the method mutates the original array or returns a new one.

Summary of JS Array Iteration

JavaScript provides multiple ways to iterate over arrays, each suited for different purposes. Classic for loops and for...of loops are flexible and simple, while higher-order methods like forEach(), map(), filter(), and reduce() enable functional-style, readable, and efficient processing. Understanding how to iterate effectively allows developers to handle dynamic data, perform calculations, transform arrays, and implement complex logic with clarity and precision. Using the appropriate iteration method ensures code that is maintainable, scalable, and aligned with modern JavaScript practices.


Practice Questions

Q1. How do you print each element of an array using a traditional for loop?

Q2. Which method is used to execute a function on every element without returning a new array?

Q3. How do you create a new array where each value is doubled?

Q4. Which loop allows you to access each value directly without an index?

Q5. What method returns a new array of elements that pass a test condition?

Q6. How do you find the total of an array like [5, 10, 15] using one function?

Q7. How is the for...in loop different from for...of when used on arrays?

Q8. What method would you use to count how many items in an array are longer than 5 characters?

Q9. Which array method does not mutate the original array but returns a new one?

Q10. How do you iterate and log both index and value using forEach()?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top