JSFiddle - React, Tailwind, and code Playground

for loop tutorial

by jonchius

JavaScript

/* 
[forloops]
// this tries to explain the "for" loop
// there is nothing to run in this example
// simply read through it as a way to understand "for" loops
*/

// begin here and go inside the loop

/* 
inside the ( ) of a for: 
"i=0" sets i as a counter that begins with 0
"i<3" means that the loop will happen 3 times
"i++" means that each time we go through the loop, i will increase by 1
*/

for (var i=0; i<3; i++) {
    
    // top
    
    // first: i is 0 at the beginning
    // next: the loop will do the stuff inside the { }
    // next: the program will go back to the top

    // next: now i is 1 ("i++" means i increases by 1), i is still less than 3
    // next: the loop will do the stuff inside the { }
    // next: the program will go back to the top
    
    // next: now i is 2 ("i++" means i increases by 1), i is still less than 3
    // next: the loop will do the stuff inside the { }
    // next: the program will go back to the top
    
    // next: now i is 3 ("i++" means i increases by 1), i is now no longer less than 3
    // next: the program will get out of the loop (go outside the { })
 
}

// now we are out of the loop: the program will continue with any remaining code

// EXTRA: further your understanding by looking at and tracing through these variations: 

for (var i=0; i<=5; i++) { 
    
    // the index (or, counter variable) can evaluate "<=" statements as well as "<"
}

for (var j=0; j<=2; j++) {
    
    // the index can have any one-word name, e.g. "j" or "k" or even "whatever"
}

for (var k=1; k<=3; k++) {
    
    // the index (in this case, "k") can start with any number!
    
}

for (var m=10; m>0; m--) {
    
    // yes, you can have a counter that moves backwards (m--) or "counts down"!
    // take care to change "<" into ">" or "<=" into ">="
    
}

var z = 20;

for (var n=0; n<z; n++) {
    
    // you can also "inject" a global integer variable like "z" into the parameters of for!
    
}