Register Login

Loop Through an Array in JavaScript

Updated Sep 20, 2022

JavaScript array can store multiple elements of the same data type as a single variable. Unlike other programming languages where an array functions like a reference storing multiple variables, in JavaScript, an array is a single variable holding more than one element.

The looping of JS arrays is a typical operation performed. In this article, users will learn about JS arrays and how to loop all elements of an array using different methods.

What is an Array?

An array is a set of elements with similar data types. Users can use an array to store data as elements and fetch them back when they need to use them in JavaScript code. Arrays are an ordered list of values with specified index values, and users can refer to these values as an element specified by that index.

JavaScript brings the concept of looping arrays, one of the common practices among users. When users create a JavaScript array, they can access every element one by one and make a list so that they can perform individual functions with them and much more.

It is where users require the loop to perform this operation. In the following sections, the article will discuss the methods of looping elements of an array with their code snippets.

What are loops in JavaScript?

JavaScript loops are a sequence of instructions (programs) that help users to repeat a specific operation a predetermined number of times until it satisfies the desired condition. It increases the code's efficiency and makes it compact.

Methods to loop through an array in JavaScript:

Following are some methods to loop through an array in JavaScript:

  1. for loop
  2. for...in loop
  3. for...of loop
  4. Array.prototype.forEach loop
  5. while loop
  6. every() method
  7. map() method
  8. do...while loop

Method 1: Using for loop for looping:

A for loop repeats every elements of an array until it satisfies a specific condition or evaluates to false. The for loop contains three parts.

These are the initialization, condition, and iteration. So, users first do not have to initialize the index while using the for loop method as the loop operates the initialization, condition, and iteration within the bracket.

Syntax:

for (initialization; condition; update statement) {
    // statement code to be executed
}

Code snippet:

array = [ 1, 2, 3, 4, 5, 6 ];
for (index = 0; index < array.length; index++) {
	console.log(array[index]);
}

Output:

Run Code

Method 2: Using for...in loop for looping:

The for...in loop in JavaScript helps users iterate over all property keys of an object.

Syntax:

for (variable in iterator) {
    // code block to be executed
}

Code snippet:

const demo = { a: 1, b: 2, c: 3 };

for (const property in demo) {
  console.log(`${property}: ${demo[property]}`);
}

Output:

Run Code

Method 3: Using for...of loop for looping:

The for...of loop in JavaScript helps users iterate over iterable objects (such as sets, arrays, strings, maps, etc.).

Syntax:

for (variable of iterator) {
    // code block to be executed
}

Code snippet:

const array1 = ['a', 'b', 'c'];
for (const element of array1) {
  console.log(element);
}

Output:

Run Code

Method 4: Using Array.prototype.forEach loop for looping:

The forEach() method calls a function and iterates over each element of the JS array. Users can also name this method as a callback function.

Compared to other methods of looping elements in Javacript, the forEach method is a more advanced method and can do much more than simply looping through each array element.

Syntax:

array.forEach(callback(currentValue [, index [, array]])[, thisArg]);

Code snippet:

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

Output:

Run Code

Method 5: Using while loop for looping:

The while statement creates a loop that operates a predefined loop statement until the test condition evaluates to true.

Syntax:

while (condition) {
    // code block to be executed
}

In the following example, we have used the while statement to output the numbers from 1 and 10 to the console:

index = 0;
array = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
while (index < array.length) {
    console.log(array[index]);
    index++;
}

Output:

Run Code

Method 6: Using every() method for looping:

The every() method checks if all elements in an array pass a test (provided as a function). It returns true if the function returns true for every element.

Else, if the function returns false for one element, the every() method returns false. Also, the every() method does not execute the function having empty elements.

a = 0;
array = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
const demo = i => i < 5;
if (array.every(demo)) {
	console.log('All are less than 5');
}
else {
	console.log('The array contains five elements that are not less than 5');
}

Output:

Run Code

Method 7: Using a map() method for looping:

A map() is a JavaScript method, a collection of elements that creates a new array where it stores each element as a key, or value pair. Map objects can store both primitive values and objects as either key or value.

When users iterate over the map objects, it returns the key, value pair in the order same as that users have inserted.

Syntax:

var new_array = array.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

Code snippet:

a = 0;
demo = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
cubing_numbers = i => Math.pow(i, 3);
cubing_numbers = demo.map(cubing_numbers);
console.log(demo);
console.log(cubing_numbers);

Output:

Run Code

Method 8: Using a do...while loop for looping:

Like the while loop, the do...while statement creates a loop that operates a predefined loop statement as long as the test condition evaluates to true.

Syntax:

do {
 // code block to be executed
} while (condition)

Code snippet:

let demo = '';
let i = 0;
do {
  i = i + 1;
  demo = demo + i;
} while (i < 10);
console.log(demo);

Output:

Run Code

Conclusion:

In this article, we have gone through eight different methods for looping through JavaScript arrays. A user must understand all of these methods and then decide which method they want to use to increase the efficiency and compatibility of their code and which method is cleaner to use and easier to read.


×