In JavaScript, there are several ways to loop through an array, depending on what you want to achieve.
Here are some common methods:
-
For loop:
A
for
loop is a basic loop that allows you to iterate through an array using an index.For example:
const array = [1, 2, 3, 4, 5]; for (let i = 0; i < array.length; i++) { console.log(array[i]); }
-
For…of loop:
A
for...of
loop is a newer loop introduced in ES6 that allows you to iterate through an array without using an index.For example:
const array = [1, 2, 3, 4, 5]; for (let value of array) { console.log(value); }
-
forEach method:
The forEach method is a built-in method of an array that allows you to iterate through an array and execute a function for each element.
For example:
const array = [1, 2, 3, 4, 5]; array.forEach(function (value) { console.log(value); });
-
map method:
The map method is another built-in method of an array that allows you to iterate through an array and create a new array based on the original array.
For example:
const array = [1, 2, 3, 4, 5]; const newArray = array.map(function (value) { return value * 2; }); console.log(newArray);
-
while loop:
The
while
loop creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.For example:
let n = 1; while (n <= 5) { console.log(n); n++; }