<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);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.