Loops in Javascript


Published on 07 April 2022


Loops in Javascript

Loop FOR in Javascript

A loop in javascript is a way to iterate through an array or set of values, displaying each element or set of elements in a certain order.

There are several types of loops, but in this article we will study the FOR loop

The "for" loop

Its way of traversing the array is by indicating from an index “i”, with a numerical value, adding each value of this index up to a final index value, where each index will correspond to the position of the array to be displayed.

The following example can be read as follows:

for an index i equal to zero; while i is less than the maximum number of indices in the array; add the index i one by one:

var colors = ["red", "white", "blue"];
for(var i=0; i < colours.length; i += 1){
  console.log(colours[i]);
}

Where "colours.length" is the number of indices of the colors array.

Where i += 1 is equivalent to i = i + 1; that is, the sum of the value i plus 1 each time the loop is traversed.

Keep in mind that spaces are not taken into account when writing our code, that is, "i += 1" is the same as "i+=1".

In the following example we are going to show the even numbers within the following set of numbers:

var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];

for(var i=0; i < numbers.length; i += 1){
  if(i % 2 == 0){
    console.log(numbers[i]);
  }
}

Where "i%2 == 0" indicates that any number i divided by 2 must be equal to 0, we write the condition "if", in case the condition is met, we show the even number for the index "i " looping through, and iterating through the "for" loop.


Previous Chapter - Next Chapter



Tips on SEO and Online Business

Next Articles

Previous Articles



All-in-one SEO software to increase the overall search engine ranking of your website