Basic for loops

by Lucille Kenney

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 iteration over the loop: if this evaluates to true, the loop will continue</li>
    <li>executed after each iteration 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 iterate 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>

JavaScript

"use strict";
//let's count from 1 to 10
for (var 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 (var index2 = 0; index2 < names.length; index2++) {
  console.log(names[index2]);
}

for (var index2 = 0; index2 < names.length; index2++) {
  var longString = names.join(", ");
  console.log(longString);
}