//PROCESS: for loops

<New code>

//PROCESS: for (i in exampleArr) { }
— loop through each value of exampleArr

//PROCESS: for (i = 0; i < 5; i++) { }
— loops variable i from from zero until four

Over and over again

Let's say that I want to repeat things a number of times in my program.

For example, let's say that I want to add together all the numbers from 1 to 10.

I can do this with the following line:

var sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;

Or I can do this with a for loop:

//INIT: start sum as zero           
var sum = 0;

var mainProcedure = function () {
    sum = getSumFromOneToTen();
    outputAnswer( sum );
}

//PROCESS: loop from 1 to 10, and add to sum each time...
var getSumFromOneToTen = function () {
    for ( i = 1; i < 11; i = i + 1 ) {
        sum = sum + i;
        
        alert( 'in loop! i=' + i + ' sum=' + sum );     // show what is happening inside the loop...
    }
    
    alert( 'finished loop! i=' + i + ' sum=' + sum );   // show the final results
    
    return sum // don't forget to return the answer!
}

//OUTPUT: display the result in #buttonID
var outputAnswer = function ( answer ) {
    document.getElementById('buttonID').innerHTML = answer;
}

Let's look at what is happening here step by step:

 value of sum   value of i  comment
0 start off in INIT
0 1 start the loop, initializing i as 1
0 1 1 < 11, so enter the loop code
1 1 sum = sum + i;
1 2 i = i + 1; //automatically add one at end of loop code block
1 2 2 < 11, so enter the loop code
3 2 sum = sum + i;
3 3 i = i + 1; //automatically add one at end of loop code block
3 3 3 < 11, so enter the loop code
6 3 sum = sum + i;
6 4 i = i + 1; //automatically add one at end of loop code block
6 4 4 < 11, so enter the loop code
10 4 sum = sum + i;
10 5 i = i + 1; //automatically add one at end of loop code block
10 5 5 < 11, so enter the loop code
15 5 sum = sum + i;
15 6 i = i + 1; //automatically add one at end of loop code block
15 6 6 < 11, so enter the loop code
21 6 sum = sum + i;
21 7 i = i + 1; //automatically add one at end of loop code block
21 7 7 < 11, so enter the loop code
28 7 sum = sum + i;
28 8 i = i + 1; //automatically add one at end of loop code block
28 8 8 < 11, so enter the loop code
36 8 sum = sum + i;
36 9 i = i + 1; //automatically add one at end of loop code block
36 9 9 < 11, so enter the loop code
45 9 sum = sum + i;
45 10 i = i + 1; //automatically add one at end of loop code block
45 10 10 < 11, so enter the loop code
55 10 sum = sum + i;
55 11 i = i + 1; //automatically add one at end of loop code block
55 11 11 is not < 11, so stop the loop

for loop syntax

for loops work like this:

for (loopVariable = 0; loopVariable < 10; loopVariable = loopVariable + 1) {
	//repeated code goes in here
}

More generally, a for loop is:

for (initial variable condition; cycle while true; variable change at end of cycle) {
	/*	repeated thing goes in here */
}

Traditionally, programmers will use i as their loop variable.

for ( i = 1; i < 11; i = i + 1 ) {
			
}

Creating a list using a for loop the traditional way

You can use for loops to create HTML code. For example, you can use them to create lists:

A list of the most common passwords used in 2014

The above uses the following code:

//INIT: create an array of the top 25 most used passwords in 2014
var passwordArr = [
    "123456",
    "password",
    "12345",
    "12345678",
    "qwerty",
    "123456789",
    "1234",
    "baseball",
    "dragon",
    "football",
    "1234567",
    "monkey",
    "letmein",
    "abc123",
    "111111",
    "mustang",
    "access",
    "shadow",
    "master",
    "michael",
    "superman",
    "696969",
    "123123",
    "batman",
    "trustno1"
];

var mainProcedure2 = function () {
    console.log( 'in mainProcedure2' );
    
    var passwordList = createPasswordList( passwordArr );
    outputList( passwordList );
}

//PROCESS: create the HTML code for a list from an array
var createPasswordList = function ( wordArr ) {
    console.log( 'in createPasswordList, wordArr: ' + wordArr );
    
    // initialize the output string and start the list code
    var outputString = "<ol>";
    
    // loop through each index of the word array ( 0 -> length - 1 )
    for ( i = 0; i < wordArr.length; i = i + 1 ) {
        console.log( 'in wordArr loop, i, outputString: ' + i + "," + outputString );
        
        //add this array value to the outputString 
        outputString = outputString + "<li>" + wordArr[ i ] + "</li>";
    }
    
    // end the list code
    outputString = outputString + "</ol>";
    console.log( 'final value of outputString: ' + outputString );
    
    // remember to return the result
    return outputString;
}

//OUTPUT: display the results inside the #outputID div
var outputList = function ( outputCode ) {
    document.getElementById('outputID').innerHTML = outputCode;
}

Creating a list the easy way using for...in loops

We can make a change to the createPasswordList function to do the same thing, but with simpler code:

//PROCESS: create the HTML code for a list from an array
var createPasswordList = function ( wordArr ) {
    console.log( 'in createPasswordList, wordArr: ' + wordArr );
    
    // initialize the output string and start the list code
    var outputString = "<ol>";
    
    // loop through each index of the word array ( 0 -> length - 1 )
    for ( i in wordArr ) {
        console.log( 'in wordArr loop, i, outputString: ' + i + "," + outputString );
        
        //add this array value to the outputString 
        outputString = outputString + "<li>" + wordArr[ i ] + "</li>";
    }
    
    // end the list code
    outputString = outputString + "</ol>";
    console.log( 'final value of outputString: ' + outputString );
    
    // remember to return the result
    return outputString;
}

for ( i in exampleVar ) {} will automatically cycle through all the possible elements of exampleVar. It is also cleaner to code.

Code example: Top 14 IT jobs by salary



...comes from the following code:

//INIT: create an array of the top 14 it jobs in 2014
//info is from http://www.businessinsider.com/14-highest-paying-tech-jobs-in-2015-2015-2?op=1
var jobsArr = [
    "Software Architect $130,891",
    "Software Development Manager $123,747",
    "Solutions Architect $121,522",
    "Analytics Manager $115,725",
    "IT Manager $115,642",
    "Product Manager $113,959",
    "Data Scientist $105,395",
    "Security Engineer $102,749",
    "QA Manager $101,330",
    "Computer Hardware Engineer $101,154",
    "Database Administrator $97,258",
    "UX Designer $96,855",
    "Software Engineer $96,392",
    "Sales Engineer $90,899"
];

var mainProcedure4 = function () {
    console.log( 'in mainProcedure4' );
    
    var jobsList = createJobsList( jobsArr );
    outputList( jobsList );
}

//PROCESS: create the HTML code for a list from an array
var createJobsList = function ( wordArr ) {
    console.log( 'in createJobsList, wordArr: ' + wordArr );
    
    // initialize the output string and start the list code
    var outputString = "<ul>";
    
    // loop through each index of the word array ( 0 -> length - 1 )
    for ( i in wordArr ) {
        console.log( 'in wordArr loop, i, outputString: ' + i + "," + outputString );
        
        //add this array value to the outputString 
        outputString = outputString + "<li>" + wordArr[ i ] + "</li>";
    }
    
    // end the list code
    outputString = outputString + "</ul>";
    console.log( 'final value of outputString: ' + outputString );
    
    // remember to return the result
    return outputString;
}

//OUTPUT: display the results inside the #outputID div
var outputList = function ( outputCode ) {
    document.getElementById('output2ID').innerHTML = outputCode;
}

Common error: infinite loops

A for loop will always run as long as the middle expression is true.

The following code will run forever because 0 < 1 will always be true. It will use the computer's processor power to the maximum until the program is halted. Usually it will also lock up or crash the browser as well.

var mainProcedure3 = function () {
    console.log( 'in mainProcedure2' );
    
    var passwordList = createBadPasswordList( passwordArr );
    outputList( passwordList );
}

//PROCESS: create the HTML code for a list from an array
var createBadPasswordList = function ( wordArr ) {
    console.log( 'in createPasswordList, wordArr: ' + wordArr );
    
    // initialize the output string and start the list code
    var outputString = "<ol>";
    
    // loop through each index of the word array ( 0 -> length - 1 )
    for ( i = 0; 0 < 1; i = i + 1 ) {
        console.log( 'in wordArr loop, i, outputString: ' + i + "," + outputString );
        
        //add this array value to the outputString 
        outputString = outputString + "<li>" + wordArr[ i ] + "</li>";
    }
    
    // end the list code
    outputString = outputString + "</ol>";
    console.log( 'final value of outputString: ' + outputString );
    
    // remember to return the result
    return outputString;
}

The most common cause of an infinite loop is forgetting to use a comparision inside the second part of the for loop definition:

For example, some people recognize that they want to loop until the index of the last index is equal to the length of the array minus one.

This works if you write:

for ( i = 0; i <= (exampleArr.length - 1); i = i + 1 ) {

}

But some people will use equals, =, instead of less than or equal to, <=:
i = (exampleArr.length - 1)

This does something deceptively cruel: Instead of comparing i and (exampleArr.length - 1), it will perform assignment so that i = (exampleArr.length - 1). And then it will return true to the loop.

This has the effect of both messing with the value of i as well as locking up the browser with an infinite loop.

Learn more