loop trough an array in javascript

In JavaScript, you can loop through an array using different methods. One of the most basic and commonly used is the for loop.

To loop through an array using a for loop, you need to know two things:

  1. the length of the array
  2. the index of each element in the array

Here's how you can do it:

index.tsx
let myArray = [1, 2, 3, 4, 5];

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

In the code above, we declare the myArray variable and assign it an array containing five elements. We then use a for loop to iterate over the array. Inside the loop, we use console.log() to print each element of the array to the console.

The for loop starts by initializing a counter variable i to 0. We then set the condition for the loop to continue executing as long as i is less than the length of the array. Finally, we increment i by 1 after each iteration.

This allows us to access each element in the array using its index, which starts at 0 and ends at the array's length minus 1.

gistlibby LogSnag