Menü schliessen
Created: September 1st 2021
Last updated: September 6th 2021
Categories: IT Development,  JavaScript Development
Author: LEXO

How to loop through an array in JavaScript

Tags:  array,  for loop,  Javascript,  loop
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

 

What is a loop?

A loop is an action that allows a certain part of a code to be repeated while some condition evaluates to true.

Define your Variable

First you have to define a Variable with an array as the value:

const food = ['Burger', 'Fries', 'Pizza'];

Create a for() loop

Now you have to create your for() loop with:

for () {}

Add the statements

for (statement 1; statement 2; statement 3) {
 //this is the codeblock
}

Statement one is executed (once) before the for loop's first run.

Statement two must be fulfilled for the loop to be executed. It's essentially the loop's condition.

Statement three is always executed after each run of the loop.

My Example

for (let i = 0; i < food.length; i++) {
};

In the first statement we create a variable named "i" (for index).

In the second statement we specify a condition, setting the requirement for the loop to be run to "i" having to be smaller than food.length.

In the third statement, we say that "i" should be incremented after each loop.

Log it to the Console

In JavaScript you can log something into your console with "console.log()".

So, we will use it to log our loop into the console. This is the final result:

for(let i = 0; i < Food.length; i++) {
  console.log(food[i]);
}

Now you should be ready to go and see it in your console.