Understanding for Loops

17 June 2020 — Written by Boahs
#js#fundamentals#loops#learning

Understanding for loops

for (let i=0; i<5;i++){
    console.log(`I'm looping!`, i);
}

Above we have one of five types of loops in javascript, and It'll repeat the code inside the block exactly five times. Let's see how it's working exactly.

for (let [initialExpression]; [condition]; [incrementExpression]){
    [statement]
}
  • The initializing expression is declared
  • The condition is evaluated, and if it returns true the initial statement will execute. If false the loop will terminate
  • The statement executes! To execute multiple statements, we use a block statement {...} to group these statments
  • If the update expression is present the [incrementExpression] is executed.

Are you wondering what the [incrementExpression] did? In javascript adding '++' behind our variable we declared 'i' will add one to it. So having i++ it's incrementing our variable i by one until it's completed that task five times.

Alright let's return back to the previous example:

for (let i=0; i<5;i++){
    console.log(`I'm looping!`, i);
}

We declared our initial expression to start at 0. It'll check that i is less than 5, and if this is true the loop will increment i by one each pass through our loop. Our loop has logic, and knows when to complete!