loop array in javascript

There are several ways to loop through an array in JavaScript, but the two most common methods are the for loop and the while loop.

Using a for loop

The for loop is the most common way of looping through an array in JavaScript. It allows you to execute a block of code a certain number of times.

index.tsx
const arr = ["apple", "banana", "orange"];

for(let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
107 chars
6 lines

In this example, we declare a variable i initialized to 0. The loop will continue to execute as long as i is less than the length of the array. Each time the loop iterates, i is incremented by 1.

Using a while loop

The while loop is another way of looping through an array in JavaScript. It allows you to execute a block of code while a certain condition is true.

index.tsx
const arr = ["apple", "banana", "orange"];

let i = 0;
while(i < arr.length) {
  console.log(arr[i]);
  i++;
}
111 chars
8 lines

In this example, we declare a variable i initialized to 0. The loop will continue to execute as long as i is less than the length of the array. Each time the loop iterates, i is incremented by 1.

Both methods have their advantages and disadvantages, but for loops are generally more commonly used for looping through arrays because they are more concise and easier to read.

gistlibby LogSnag