The for
cycle is basically an iterative structure to execute the same code segment a desired number of times, this desired number of times is controlled by a condition that will evaluate whether or not it continues executing the internal code lines. The basic parts are
for (inicialización; condición; incremento) //here your code loop
The initialization serves as the basis or beginning of the cycle, ie for example if you want to execute 20 lines of code in a for
, you could have many options, I would say infinite variations.
for (let i = 0; i < 20; i++) { ... }
for (let i = 10; i < 30; i++) { ...}
The two forms will work. but mostly the initial variable of the cycle for
is used in 0, this is so that apart from serving as variable iteradora
also works as indice
to reference fixes positions and since they start from 0. It is customary to start in 0
. Beware that you can initialize more than one variable in this part.
The second part is the condition, the essential part of the cycle, in this part it will be evaluated if the cycle continues or not. It could be understood as a if
if the result is true then it continues executing and if it is false it leaves the cycle. In this part you can have different types of comparison and more than one condition always following closely the logical tables of truth.
Mostly as in the initialization, the length
is placed, that is, the number of times you want the code to be executed or the length of the array to avoid getting an exception of type IndexOfRange
when used as an index. But it could simply be a variable booleana
and act the same way. (ejm)
// se ejecutará 5 veces ya que cuando i=5, cambiará la bandera
// y la condición será false y saldrá del for
let isNext= true;
for (let i = 0; isNext; i++) {
if(i==5) isNext = false;
else console.log(i)
}
This second part always must return a value booleano
, true or false
The increment is mostly used to change the state of the iterator variable, there are also different variations and as in the initialization, it can contain more than 1
variable incremented, in addition to increase it can also be decremented. these two can be 1 in 1 (++) or (-) or whatever you want i+=2
(2 in 2) i-=2
(2 in 2) em> descending. You have to have some clear things in this part, for this maybe you can serve this question (ejm)
//Se ejecutará 10 veces , pero se hace de forma descendente el conteo.
for (var i = 10; i >0; i--) { ...}
// se ejecutará 5 veces dado que hace el decremento de 2 en 2
for (var i = 10; i >0; i-=2) { ...}