How to loop through an array in JavaScript

In JavaScript, arrays serve as a powerful means to hold a set of items. One fundamental operation we can perform on an array is to loop or iterate through each of its elements. Let’s explore various methods to traverse through an object.

1. Using the for loop

The for loop utilized with arrays is a technique that has existed for a long time. This approach provides full control over the loop index and allows for the possibility of exiting the loop at any point you desire.

Example

// Example array
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

// Loop through the array using a for loop
for (let i = 0; i < fruits.length; i++) {
  // Print each fruit to the console
  console.log(fruits[i]);
}

Explanation:

  • The for loop starts from a new variable i set to 0.
  • The loop will continue as long as the variables inside array objects are less than i (fruits.length).
  • In each loop, fruits[i] gets the current element, which is then displayed in the dialogue box.
  • The i value increases after each iteration.

Output:

Output

Apple
Banana
Cherry
Date

2. Using the for...of loop

The for...of loop is a more contemporary approach that was introduced in ES6 (ECMAScript 2015). It offers a more straightforward syntax for traversing iterable entities, including arrays.

Example

// Example array
let colors = ['Red', 'Green', 'Blue', 'Yellow'];

// Loop through the array using for...of loop
for (let color of colors) {
  // Print each color to the console
  console.log(color);
}

Explanation:

  • The for...of loop essentially functions by letting each colour take a turn in displaying the colours.
  • Loop variable colour becomes the current element in each iteration.
  • It is more elegant in its approach because it is more direct and eliminates the need for manual index management.

Output:

Output

Red
Green
Blue
Yellow

3. Using the forEach method

The forEach method is a function associated with arrays that executes a specified function for every element within the array. It is classified as a higher-order function, making it quite accessible for novices due to its clear and understandable syntax.

Example

// Example array
let numbers = [1, 2, 3, 4];

// Loop through the array using forEach
numbers.forEach(function(number) {
  // Print each number to the console
  console.log(number);
});

Explanation:

  • The forEach method is a function that takes a callback as an argument.
  • The function is the one that runs for each member in the numbers array.
  • The number stands like the current array element.

Output:

Output

1
2
3
4

4. Using the map method

The map method is a function that accepts a function as its initial input parameter, followed by an array.

Example

// Example array
let originalNumbers = [1, 2, 3, 4];

// Loop through the array using map
let doubledNumbers = originalNumbers.map(function(num) {
  return num * 2;
});

// Print the new array
console.log(doubledNumbers);

Clarification:

  • The map function, which generates a new array containing elements that result from applying a provided function to each item, is referred to as a prefix to the array.
  • In this scenario, the function takes each element and multiplies it by 2.

Output:

Output

[2, 4, 6, 8]

5. Using the while loop

A while statement serves as a looping construct that continues to execute as long as the specified condition remains true.

Example

// Example array
let animals = ['Dog', 'Cat', 'Elephant'];
let index = 0;

// Loop through the array using while loop
while (index < animals.length) {
  // Print each animal to the console
  console.log(animals[index]);
  index++; // Increment the index
}

Explanation:

  • To while loop will be running until the expression for it is index< animals.length is reached.
  • The important step here is animals[index] to access the current element using animals' array.
  • The counter is also incremented at each step.

Output:

Output

Dog
Cat
Elephant

6. Using the do...while loop

The do...while loop requires that the body of the loop is executed a minimum of one time prior to evaluating the condition to determine if it holds true.

Example

// Example array
let cities = ['New York', 'Los Angeles', 'Chicago'];
let i = 0;

// Loop through the array using do...while loop
do {
  // Print each city to the console
  console.log(cities[i]);
  i++; // Increment the index
} while (i < cities.length);

Explanation:

  • The do...while loop is designed to execute its block of code initially, followed by a condition evaluation.
  • Upon completing the first iteration, it verifies whether i < cities.length to determine if it should execute again.

Output:

Output

New York
Los Angeles
Chicago

7. Using the reduce method

The reduce function processes each element within a designated array to produce a singular output value that is derived from the reducer function. This technique involves manipulating an array to yield a final result that encompasses more than just a straightforward operation. Although it does not resemble a conventional loop, it evaluates all entries and can serve to formulate the final outcome.

Example

// Example array
let values = [5, 10, 15];

// Calculate the sum using reduce
let sum = values.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

// Print the sum
console.log(sum);

Explanation:

  • Using a reducer is like a sequence of applications and you have to provide the first element of it which is 0 in this case.
  • This reducer function is the heart of the process and the accumulator is the true result while the current value points out the elements.
  • The aggregate (sum) is obtained by the array element through the function.

Output:

8. Using the for...in loop

The for...in loop serves the purpose of iterating through the enumerable properties of an object. While it is designed to function with array elements, this characteristic makes it less favorable for array usage, as it treats indices as strings rather than numbers.

Example

// Example array
let languages = ['JavaScript', 'Python', 'Java'];

// Loop through the array using for...in loop
for (let index in languages) {
  // Print each language to the console
  console.log(languages[index]);
}

Explanation:

  • The for...in loop enumerates the indices of the languages array.
  • index is a string that represents the index number, languages[index] is used to access the corresponding element.
  • Any unnecessary iteration of the loop in the bibliography can result in unexpected outcomes.

Output:

Output

JavaScript
Python
Java

9. Using the entries Method

This approach generates a novel type of bits that the browser can process, referred to as an Array of iterators. Every entry holds a tuple that consists of the element's position along with its corresponding value.

Example

// Example array
let countries = ['USA', 'Canada', 'Mexico'];

// Get the iterator object for the array
let iterator = countries.entries();

// Loop through the iterator using a for...of loop
for (let [index, country] of iterator) {
  // Print the index and the country
  console.log(index, country);
}

Explanation:

  • The iterator returned has keys and values.
  • The for...of loop itemizes each iterator, the arrays produced in the process contain the index and the element.
  • The destructuring assignment [index, country] provides an easy way to take out both the position and the value from an array.

Output:

Output

0 USA
1 Canada
2 Mexico

10. Using the Array.from Method

The Array.from method facilitates the creation of a new array object from an iterable or array-like entity. This approach diverges from conventional looping techniques; instead, it allows for the conversion of iterable constructs (like strings) into arrays. Once converted, these arrays can be traversed using standard iteration methods.

Example

// Example string
let name = 'John';

// Convert string to array using Array.from
let nameArray = Array.from(name);

// Loop through the array using a forEach loop
nameArray.forEach(function(char) {
  // Print each character to the console
  console.log(char);
});

Explanation:

  • The Array.from method changes the string name to an array where each element is a character from the string.
  • Next, the resulting Array is converted to the forEach method which is then given over to the nameArray.
  • For each repetition, the current character that is the printed character of the console is presented on the screen.

Output:

Output

J
o
h
n

Conclusion

If you have experience with the JavaScript programming language, you may recognize various methods that it offers through its array prototypes. JavaScript includes multiple techniques for iterating over arrays, each designed for specific purposes and advantages. The choice of loop—be it a traditional for loop, a for-each loop, or a while loop—will depend on your preference. It is advisable to utilize the loops that you find most comfortable.

Input Required

This code uses input(). Please provide values below: