How to iterate an array in JavaScript

js

Table of Contents

Introduction

JavaScript arrays are fundamental data structures that store collections of elements. Effectively iterating over arrays is a crucial skill for every JavaScript developer.

In this article, we'll explore various methods to iterate through arrays in JavaScript, providing insights into when and why you might choose one method over another.

Iterating array using for loop

The classic for loop is a staple in JavaScript programming. It allows precise control over the iteration process, making it suitable for scenarios where index manipulation is necessary. Its simplicity and efficiency make it a preferred choice for many developers.

Example:
Double the value of each element at even indices of the array

Double the value of each element at even indices of the array // Original array of numbers const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Display the original array console.log("Original Array:", numbers); // Double the value of elements at even indices using a for-loop for (let i = 0; i < numbers.length; i++) { // Check if the index is even if (i % 2 === 0) { // Double the value at even indices numbers[i] *= 2; } } // Display the modified array console.log("Modified Array:", numbers);

In this example:

  1. We start with an array of numbers (numbers).
  2. We use a for loop to iterate over each element in the array.
  3. The condition i % 2 === 0 checks if the current index (i) is even.
  4. If the index is even, we double the value of the element at that index using *numbers[i] = 2.

Iterating array using for...of loop

Introduced in ECMAScript 2015 (ES6), the for...of loop provides a cleaner syntax for iterating over iterable objects, including arrays. It simplifies the code and enhances readability.

Example:
Calculate the sum of an array of numbers using for...of loop

// Original array of numbers const numbers = [1, 2, 3, 4, 5]; // Initialize a variable to store the sum let sum = 0; // Use a for...of loop to iterate over the array for (const number of numbers) { // Add each number to the sum sum += number; } // Display the sum console.log("Sum of the numbers:", sum);

In this example:

  1. We start with an array of numbers (numbers).
  2. We use a for...of loop to iterate over each element in the array.
  3. The loop assigns each element to the variable number during each iteration.
  4. Inside the loop, we add the current number to the sum variable.

Iterating array using forEach method

The forEach method is a powerful tool for iterating through arrays, especially when you want to perform an action on each element of the array. It accepts a callback function that is executed for each element in the array.

Example:
Print a greeting message for each name in the array using the forEach method.

// Original array of names const names = ['Alice', 'Bob', 'Charlie', 'David']; // Define a callback function to print a greeting function greetPerson(name) { console.log(`Hello, ${name}!`); } // Use forEach with the callback function to iterate over the array names.forEach(greetPerson);

In this example:

  1. We define a named function, greetPerson, that takes a name parameter and prints a greeting message.
  2. We use the forEach method to iterate over each element in the names array.
  3. Instead of an anonymous function, we pass the named greetPerson function as the callback to forEach.
  4. The forEach method automatically calls the greetPerson function for each element in the array, passing the current element as an argument.

Iterating array using the map method

The map method is a powerful and versatile array method introduced in ECMAScript 5 (ES5) that is used to transform each element of an array based on a provided callback function. It creates a new array with the results of the callback function on every element in the array.

Example:
Convert the array of temperatures in Celsius to Fahrenheit using the map method.

// Original array of temperatures in Celsius const celsiusTemperatures = [0, 10, 20, 30, 40]; // Use the map method to convert temperatures to Fahrenheit const fahrenheitTemperatures = celsiusTemperatures.map(function(celsius) { // Convert Celsius to Fahrenheit: F = (C * 9/5) + 32 return (celsius * 9/5) + 32; }); // Display the original and converted temperatures console.log("Celsius Temperatures:", celsiusTemperatures); console.log("Fahrenheit Temperatures:", fahrenheitTemperatures);

In this example:

  1. We start with an array of temperatures in Celsius (celsiusTemperatures).
  2. We use the map method to create a new array (fahrenheitTemperatures) by applying a conversion formula to each element in the original array.
  3. The callback function inside map takes a temperature in Celsius as a parameter and returns the corresponding temperature in Fahrenheit.
  4. The resulting fahrenheitTemperatures array contains the converted temperatures.

Iterating array using filter method

The filter method is an essential array method introduced in ECMAScript 5 (ES5) that allows you to create a new array containing elements that satisfy a specific condition. It iterates through each element in the array, applying a provided callback function and includes only the elements that pass the specified test in the new array.

Example:
Filter out odd numbers from the array using the filter method

// Original array of numbers const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Use the filter method to create a new array of odd numbers const oddNumbers = numbers.filter(function(number) { // Return true to include odd numbers, false to exclude even numbers return number % 2 !== 0; }); // Display the original and filtered arrays console.log("Original Numbers:", numbers); console.log("Odd Numbers:", oddNumbers);

In this example:

  1. We start with an array of numbers (numbers).
  2. We use the filter method to create a new array (oddNumbers) containing only the odd numbers.
  3. The callback function takes a number as a parameter and returns true to include the number in the new array if it's odd or false to exclude it if it's even.

Iterating array using reduce method

The reduce method is a versatile array method introduced in ECMAScript 5 (ES5) that is used to accumulate or reduce an array into a single value. It iterates through the array, applying a provided callback function that "reduces" the array to a single value.

Example:
Calculate the sum of all elements of the array using the reduce method

// Original array of numbers const numbers = [1, 2, 3, 4, 5]; // Use the reduce method to calculate the sum const sum = numbers.reduce(function(accumulator, currentValue) { // Accumulate the sum by adding the current value return accumulator + currentValue; }, 0); // Initial value of the accumulator is 0 // Display the original array and the sum console.log("Original Numbers:", numbers); console.log("Sum of Numbers:", sum);

In this example:

  1. We start with an array of numbers (numbers).
  2. We use the reduce method to accumulate the sum of all elements.
  3. The callback function takes an accumulator and currentValue as parameters and returns the sum of the two.
  4. The reduce method initializes the accumulator with a value of 0.

Certainly! Let's elaborate on a couple of other array methods in JavaScript: some and every.

Iterating array using some method

The some method tests whether at least one element in the array passes a provided condition. It returns a Boolean value indicating whether some elements in the array satisfy the testing function.

Example:
Check if even numbers exist in the array using some method.

// Original array of numbers const numbers = [1, 3, 5, 6, 7]; // Use the some method to check if at least one element is even const hasEvenNumber = numbers.some(function(number) { // Return true if the number is even, otherwise false return number % 2 === 0; }); // Display the original array and the result console.log("Original Numbers:", numbers); console.log("Has Even Number:", hasEvenNumber);

In this example, some checks if at least one element in the array is even, and hasEvenNumber is true because the array contains the number 6.

Iterating array using every method

The every method tests whether all elements in the array pass a provided condition. It returns a Boolean value indicating whether every element in the array satisfies the testing function.

Example: Check if all numbers in array are positive using every method

// Original array of numbers const numbers = [1, 3, 5, 7, 9]; // Use the every method to check if all elements are positive const allPositive = numbers.every(function(number) { // Return true if the number is positive, otherwise false return number > 0; }); // Display the original array and the result console.log("Original Numbers:", numbers); console.log("All Positive:", allPositive);

In this example, every check if all elements in the array are positive, and allPositive is true because all numbers in the array are greater than 0.

Iterating array using while loop

The while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. The loop continues iterating as long as the condition remains true.

Example:
Countdown

// Initialize a counter let count = 5; // Use a while loop to create a countdown while (count > 0) { console.log(count); count--; } console.log("Blast off!");

In this example, the while loop iterates as long as the count is greater than 0, printing the countdown values and decrementing count in each iteration.

Iterating array using do...while loop

The do...while loop is similar to the while loop, but the block of code is executed at least once before the condition is checked. This ensures that the code inside the loop runs at least once, even if the condition is initially false.

Example:
User Input Validation

let userInput; do { userInput = prompt("Enter a number greater than 5:"); } while (parseInt(userInput) <= 5); console.log("Valid input:", userInput);

In this example, the do...while loop prompts the user to enter a number until a number greater than 5 is provided. The loop guarantees that the prompt is shown at least once.

The for...in loop is used to iterate over the enumerable properties of an object. It is particularly handy for iterating over the keys or properties of an object rather than the elements of an array. While it can be used with arrays, caution is advised due to potential issues with inherited properties.

for (const key in object) { // code to be executed for each enumerable property of the object }

Share this

Share on social media