Basic for loops

for CSCI E3, Harvard University author(s): Larry Bouthillier

by mspears

HTML

<b>Open your console to see the output from this code!</b>
<p>In the first example, we set our three expressions in the <i>for</i> loop.  Remember, they are:
    <ol>
        <li>the initial expression: this is executed once before the loop runs, and typically sets the initial condition for the counter: in this case, setting <i>index</i> equal to 1 
        </li>
        <li>the test to run before each <span class="hilite">iteration</span> over the loop: if this evaluates to true, the loop will continue</li>
        <li>executed after each <span class="hilite">iteration</span> through the loop. In this case we use it to increment <i>index</i> to the next value</li>
    </ol> 
</p>

<p>In the second example, we create an array of names, and use the loop to <span class="hilite">iterate</span> over the array and output its contents to the console. </p>
<p>How would you modify the second loop so that all of the names are printed on one line? </p>


<p>From the dictionary:<br>
<span class="hilite">Iterate</span> means make repeated use of a computational procedure; perform iteration.   Repeat, go through again, go over again.  
</p>
<p>
<span class="hilite">Iteration</span> is the repetition of a process.

</p>

CSS

.hilite {
  background-color: yellow;
}

JavaScript

"use strict";
//let's count from 1 to 10
for (let index=1; index<=10; index++){
 console.log(index);   
}

//now let's iterate over an array
var names = ["Frodo", "Bilbo", "Samwise", "Merry", "Pippin"];

console.log("Some of my favorite hobbits are:");

// remember that arrays start at zero
// so we will loop from 0 to the length of the array
for (let index=0; index<names.length; index++){
     console.log(names[index]);   
}