<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
Creating a list the easy way using for...in
loops
Instead of using .join()
, programmers usually use
a for
loop to repeat things over and over.
The simplest way to do this is by looping through each of the
members in an array:
for ( i in exampleArr ) { ... }
Here is an example of an easy way to make a
<ol><li></li></ol>
list from an array of passwords:
//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 13 IT jobs by salary
...comes from the following code:
//OUTPUT: display the results inside the output div
var outputList = function ( outputCode ) {
console.log( 'in outputList. outputCode = ' + outputCode );
document.getElementById('outputJobsListId').innerHTML = outputCode;
}
//PROCESS: create the HTML code for a list from an array
var createJobsList = function ( jobsArr ) {
console.log( 'in createJobsList, jobsArr: ', jobsArr );
// 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 jobsArr ) {
console.log( 'in jobsArr loop, i, outputString: ' + i + "," + outputString );
//add this array value to the outputString
outputString = outputString + "<li>" + jobsArr[ i ] + "</li>";
}
// end the list code
outputString = outputString + "</ul>";
console.log( 'final value of outputString: ' + outputString );
// remember to return the result
return outputString;
}
//INIT: set up the information inside the jobs array
var initJobsArr = function ( ) {
console.log( 'in initJobsArr...' );
//INIT: create an array of IT job most in demand in 2019
// from https://www.cio.com/article/3235944/hiring-and-staffing/hiring-the-most-in-demand-tech-jobs-for-2018.html
// Sorry about the long line - didn't want to break the link)
var jobsArr = [
"Data scientist $121,500",
"Security professionals (information, data, network, systems) $120,000",
"Database developer $118,000",
"DevOps engineer $110,500",
"Business intelligence analyst $106,000",
"Cloud systems engineer $103,000",
"Developer (web, software, mobile) $100,000",
"Cloud architect $94,500",
"Network administrators $89,000",
"Systems administrators $81,750",
"Full-stack developers $79,250",
"IoT specialists $71,500",
"Help desk and desktop support specialists $45,740",
];
return jobsArr
}
//MAIN
var mainJobsListProcedure = function () {
console.log( 'in mainJobsListProcedure' );
var jobsArr = initJobsArr();
var jobsList = createJobsList( jobsArr );
outputList( jobsList );
}
//INPUT EVENT: trigger mainJobsListProcedure when #jobsListButtonId is clicked
document.querySelector( '#jobsListButtonId' ).onclick = mainJobsListProcedure;
Over and over again: creating loops with full control
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:
//OUTPUT: display the result in #buttonId
var outputAnswer = function ( answer ) {
console.log( 'in outputAnswer. answer=' + answer );
document.querySelector( '#forLoopButtonId' ).innerHTML = answer;
}
//PROCESS: loop from 1 to 10, and add to sum each time...
var getSumFromOneToTen = function () {
console.log( 'in getSumFromOneToTen...' );
//INIT: start sum as zero
var sum = 0;
for ( i = 1; i < 11; i = i + 1 ) {
sum = sum + i;
// show what is happening inside the loop...
console.log( 'in loop! i=' + i + ' sum=' + sum );
}
// show the final results
console.log( 'finished loop! i=' + i + ' sum=' + sum );
return sum // don't forget to return the answer!
}
//MAIN
var mainForLoopProcedure = function () {
console.log( 'in mainForLoopProcedure...' );
sum = getSumFromOneToTen();
outputAnswer( sum );
}
//INPUT EVENT:
document.querySelector( '#forLoopButtonId' ).onclick = mainForLoopProcedure;
Check out the developer's console to trace the flow of the program. 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 2017
The above uses the following code:
//OUTPUT: display the results inside #outputTraditionalLoopId
var outputPasswordList = function ( outputCode ) {
console.log( 'in outputPasswordList. outputCode=' + outputCode );
document.getElementById('outputTraditionalLoopId').innerHTML = outputCode;
}
//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;
}
//INIT: create the array of passwords
var initPasswordArr = function () {
console.log( 'in initPasswordArr...' );
//INIT: create an array of the top 25 most used passwords in 2017
// from https://en.wikipedia.org/wiki/List_of_the_most_common_passwords
var passwordArr = [
"123456",
"password",
"12345678",
"qwerty",
"12345",
"123456789",
"letmein",
"1234567",
"football",
"dragon",
"admin",
"welcome",
"monkey",
"login",
"abc123",
"starwars",
"123123",
"dragon",
"passw0rd",
"master",
"hello",
"freedom",
"whatever",
"qazwsx",
"trustno1"
];
return passwordArr;
}
//MAIN
var mainTraditionalLoopProcedure = function () {
console.log( 'in mainTraditionalLoopProcedure' );
var passwordArr = initPasswordArr();
var passwordList = createPasswordList( passwordArr );
outputPasswordList( passwordList );
}
//INPUT EVENT: trigger the main procedure when the button is pressed
document.querySelector( '#traditionalLoopButtonId' ).onclick = mainTraditionalLoopProcedure;
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.
//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;
}
//MAIN
var mainInfiniteLoopProcedure = function () {
console.log( 'in mainInfiniteLoopProcedure...' );
var passwordArr = initPasswordArr();
var passwordList = createBadPasswordList( passwordArr );
outputList( passwordList );
}
//INPUT EVENT: trigger mainInfiniteLoopProcedure when #infiniteLoopButtonId is clicked
document.querySelector( '#infiniteLoopButtonId' ).onclick = mainInfiniteLoopProcedure;
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
.
And then it will return true to the loop.
i = (exampleArr.length - 1)
This has the effect of both messing with the value of i as well as locking up the browser with an infinite loop.