Control structures: for to perform loops - 13

- Andrés Cruz

En español

Control structures: for to perform loops - 13

From here we finish the conditional blocks and enter another universe in which we see how to create loops, that is, a control structure that allows us to repeat the same instruction or the instructions that define a finite set of times; those we specify; Its use is very structured and is like the following:

for(initialization; condition; update) { statement 1 statement 2 ... statement N }

In the initialization phase we have to set what will be the initial value of a variable that is responsible for saving the record of the iteration that is being carried out and that is increased in the update phase.
The condition specifies the stopping condition; that is to say; When this is not met (it returns false) the repetition of the for is simply stopped.
The update phase is the update of the value that we do for each iteration to the variable that we initialize in the initialization phase.

Example of for

The traditional example of a for looks like this:

n=0
for(var i = 0; i < 5; i++) {
  n=n+1;
}
n

Shortened way to add a unit to an element

n=0
for(var i = 0; i < 5; i++) {
  n++;
}
n

The for or loops in general are quite useful when we have collections to iterate, which later we will see what these collections are; but abstract a little, and suppose that we have collections of elements, which can be posts, products, etc., it all depends on the purpose of the application you are building, you have a set of values that you want to display in some way; for example, in our case of interest, which is web development, you have 3 values for which you want to build a list like the following:

Listado de Post

Perfectly with the for you can repeat the instructions that allow you to build one of those boxes given this set of values; but we will deal with that later.

Now another example; what happens if we add the value of i:

n=0
for(var i = 0; i < 5; i++) {
  n=n+i;
}
n

Now we are going to do another example using the console.log function; at this point we have not seen that it is a function but you can see it as if it were simply a block with a set of instructions that does some particular operation; In the case of the console.log it would be to display a message through the console:

for(var i = 0; i < 5; i++) {
   console.log(i);
}

And this way you can see the value of i in a more effective way.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.