drawing


Goal


The goal of this tutorial is to create a loop to execute our code a defined number of times


Info


Imagine that you have a something() function that only writes “Hello”:

function something(){
  console.log("Hello");
}

Imagine now that you want to execute it 10 times. Like this:

    something();
    something();
    something();
    something();
    something();
    something();
    something();
    something();
    something();
    something();

This is not the right way to do it, and you know it.

For these kind of things we use Loops.

Loops allows us to repeat some code a defined number of times.

We have a lot of loops but today we take care about the FOR.


Syntax


for ([initialization]; [condition]; [final-expression]){
    statement
}
  • initialization

    An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable.

  • condition

    An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

  • final-expression

    An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable. A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ … }) to group those statements. To execute no statement within the loop, use an empty statement (;).


Result


Now we can execute some interesting stuff:

for(var i = 1; i < 10; i++){
    something();
}

Our something() function now is executed 10 times with this output. Good Job!

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello