For Loops

Tue, Nov 07, 2017

What is a For Loop?

A For Loop is a way to repeatedly execute a block of code over and over again.

For Loops work well with Arrays, since they take advantage of the index part of the array.

Remember, the index is the the part of the array that specifies which data element we want to retrieve.

var someArray[index];

There are times in which we want to repeat a piece of code over and over again. This is called a loop. Why do we want to repeat a piece of code? The most typical example of a loop is the ability to iterate through a large dataset — like an array, changing or retrieving values. There are actually several different types of loops in JavaScript, such as For Loops, While Loop, Do … While Loop, and For … In Loop.

Structure of a For Loop

The most common loop is the For Loop, which uses the For keyword. It is best to master the For Loop first before learning the others. In many cases, the For Loop can accomplish the same results as the others, but using more verbose language.

The for-loop consists of three parts.

  1. A start value,
  2. A condition and
  3. An increment.

(Each is separated by semi-colons.)

for(start-value; condition; increment){
    //code that will be executed over and over
}

The For Loop is designed to count from the start value you set in the start value, executing the code you specify until the condition is met. It counts by increments you give in the third part of the expression. This is a basic example of the for loop:

for(var i=0; i < 20; i++){
    //code will execute 20 times
}

In the above example, we set i = 0 as our start value. The variable we created, i, is also called the iterator because it iterates each time the loop is run. The for-loop will run the code between the curly braces as long as the condition i < 20 is true. Each time the code is run, the last part of the For Loop, called the increment, will execute. In our case, we increment our variable by one each time using i++. The shorthand i++ is a method of increasing any number variable by one.

Here is another example of using a For Loop:

for(var i=0; i < 5; i++){
    console.log("Some message")
}

//console output:
//some text
//some text
//some text
//some text
//some text

From the above example, you can see when we run the loop, it writes the text to the console five times. In our For Loop, we initialized the i variable as zero, and we increment it by one until the condition i < 5 is met. Once the i variable hits five, the for loop terminates, and the rest of the program continues after it.

Using the i Iterator in a For Loop

We typically use i as a variable to iterate through, but any variable would be fine to use. As the loop executes over and over, the i will increment, increasing by one each time. You can use this i within the code block as needed.

for(var i=0; i < 5; i++){
    console.log("The value of i is: " + i );
}

//output:
//The value of i is: 0
//The value of i is: 1
//The value of i is: 2
//The value of i is: 3
//The value of i is: 4

As we see from the example above, the i variable increases by one each time. It starts on zero because that is what we specified during the first part of the For Loop. It never hits five, because our condition prohibits it.

Using the iterator is a powerful tool because it works as the index of an array.

var myarray = ["a", "b", "c", "d", "e", "f", "g", "h"];

for(var i=0; i < 8; i++){
    console.log(myarray[i]);
}

//output:
//a
//b
//c
//d
//e
//f
//g
//h

We can also use the .length property to determine the length of an array dynamically. This allows us to set our condition in a way so that if items are ever added to the array, we don’t have to modify our For Loop.

var myarray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];

for(var i=0; i < myarray.length; i++){
    console.log(myarray[i]);
}

Omitting statements

Turns out, not all the statements in a For Loop are required. You must still include the semi-colon. In these situations, you would use an existing variable for your condition.

var currentPhoto = 0;
var totalPhotos  = 100;

for(; currentPhoto < totalPhotos; currentPhoto++){
    //will keep iterating until currentPhoto is equal to totalPhotos
}

Technically, you could omit all of the statements, but that would create an infinite loop (and could crash the browser.) So, it’s best not to do this unless you’re going to break the loop.

//infinite loop
for(;;){
    
    //need some way to break the loop so it doesn't crash the browser
    if(j == 100){
        break;
    }

}

The For…In Loop

This is an important type of For Loop that will show up often. The For In Loop is a way to iterate through every property in an object.

It takes two statements:

  1. a declared variable,
  2. an object with properties.

The declare variable will be each property as the loop runs. This is a convenient way to access each property in an object.

var person = {firstName: "John", lastName: "Smith", age:44, hairColor:"brown"};

for (var prop in person){
    console.log(prop);
}

//outputs:
//firstName
//lastName
//hairColor

You can also use the property variable you create, to access the values in the original object like so:

var person = {firstName: "John", lastName: "Smith", age:44, hairColor:"brown"};

for (var prop in person){
    console.log(person[prop]);
}

//outputs:
//John
//Smith
//44
//brown

ForEach loop

If you’re working with an array, there is an easy function built into JavaScript that allows you to loop through the array. This method also provides the convenience of having the iterator be equal to that specific element in the array it’s looping over during each round. Case in point:

var arr = ["John", "Joe", "Jim"];

arr.forEach(function(d){

    //each pass d will be equal to an element in array
    console.log(d);//John
                   //Joe
                   //Jim

});

Exercise

In the exercise below, we will create a waffle-type graphic in D3, and add data to is using a For Loop.

Lesson was inspired by this graphic.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Person Grid Example</title>
    <style type="text/css">
        #graphic{
            display:block;
            margin: 10px auto;
        }
    </style>
</head>
<body>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
    
    var width  = 900,
        height = 800;
    
    var svg = d3.select("body")
        .append("svg")
        .attr("id", "graphic")
        .attr("width", width)
        .attr("height", height);

    var howManyAcross = Math.floor(width / 25);

    var thedata = [];

    /*
     * Your job is to create a For Loop and populate thedata variable with color strings.
     *
     * You can add to a color string to an Array by executing thedata.push("#000000");
     *
     * Use conditional statements to setup different color strings for different segments of the chart.
     */

    


    //make sure to populate the data before the code below
    svg.selectAll("g")
        .data(thedata)
        .enter()
        .append("g")
        .attr("transform", function(d, i){ return "translate(" + ((i % howManyAcross) * 25) + "," + (Math.floor(i/howManyAcross) * 70) + ")"})
        .append("path")
        .attr("d", "M18,8c0-4.417-3.582-8-8-8C5.582,0,2,3.583,2,8c0,4.418,3.582,8,8,8C14.418,16,18,12.418,18,8z M13.291,16H10H6.708c-3.682,0-6.666,2.984-6.666,6.666V41.82c0,1.75,1.334,3.172,3.038,3.342v19.779H16.92V45.162c1.703-0.17,3.037-1.592,3.037-3.342V22.666C19.957,18.984,16.973,16,13.291,16z")
        .style("fill", "white")
        .transition()
        .duration(100)
        .delay(function(d,i){ return i * 20;})
        .style("fill", function(d){ return d; });

</script>
</body>
</html>