The For Loop and The Break Keyword
Using for loops, we've shortened the
long arrays from 24 or 60 lines each to 4 lines each. Our time script has been shortened by about 140 lines.
I feel so clean.
Repetition using for loop
So far all our code has been linear, which is fine for coding different statements and expressions. But what if you have many statements that are exactly the same? As you now know, coding the same statement over and over is very cumbersome.
There are while loops, do while loops, for in loops and continue loops. We'll focus on the most common, the
for loop.
For loops have 3 main parts: the for keyword, the iteration statements contained in parentheses, and the for body's statements.
for (iteration statements) {
statements
}
An iteration is each repetition of a looping statement.
There are also 3 parts to the iteration statement: the initialization expression, the condition, and the update statement. They all belong in parentheses and are separated by semi-colons.
for (initialization expression; condition; update statement) {
statements
}
The
initialization expression sets a variable equal to an integer value, also known as a counter. The integer value will vary depending on where you want the counter to begin.
The
condition statement is somewhat like an if statement. As long as the condition is true, the statements in the body of the for loop will execute. When the condition evaluates to false, the statements are no longer executed and the JavaScript engine continues on to any statements following the loop. Think of the condition as the loop's goal, it will cause the loop to iterate until the goal is reached.
The condition statement in our working example uses the length property. Length refers to the the actual number of elements in an array, which can be declared in the parentheses of the array constructor.
( hourNames = new Array(24) )
In this case, length equals 24 since there are 24 elements in the hourNames array. Since element numbers start at zero, length is always one more than the last element slot number, e.g. the last element slot number in the hourNames array is 23. If you wanted to access the last element in the hourNames array without knowing its slot number, the syntax would be:
hourNames[hourNames.length-1]
If you wanted to add another element to an array but do not know (or care) how many elements are currently in the array, you can substitute the value of the length property for the element number:
hourNames[hourNames.length]="25 o'clock". The value of '25 o'clock' will be assigned to slot number 24 in the array, assuming the array already consists of 24 elements.
**Length is also a property of string objects. someString.length returns the number of characters in the string being referenced.**
The
update statement is what updates the value of the counter. It doesn't actually change the value in all cases, it just tells the engine to perform the evaluation on an incremented value of the counter. If the counter in the initialization expression was never updated, we'd end up with an infinite loop. Update statements use increment (++) operators and decrement (--) operators, depending on how you construct the loop. Usually you will see increment operators used on the right side of the counter variable, which is known as a postfix operator.
x = 3
y=x++ (sets y to 3 and increments x to 4)
y=++x (increments x to 4 and sets y to 4)
for (var i = 1; i <= 5; i++) {
alert("this iteration, i equals:" + i)
}
See it in action.
In the above example, the counter is set to 1, then the condition states that as long as the counter is less than or equal to five, alert its value. The update statement is used to add 1 to the value of i for each iteration. Try this one on your own first with the update statement, then without.
for (var i = 5; i > 0; i--) {
alert("this iteration, i equals:" + i)
}
See it in action.
The Break Keyword
The break keyword is used to do just that - break out of a loop. You would use it when a certain condition is met, and looping is no longer neccessary:
for (var i = 1; i <= 5; i++) {
if(i == 2){
alert("i equals 2 so I am no longer going to loop")
break
}
else{
alert("this iteration, i equals:" + i)
}
}
See it in action.
Jumping back to the time script, loops were used to generate array element indices and their values. Look at the seconds array written manually:
var allSeconds = new Array(60)
allSeconds[0]="00"
allSeconds[1]="01"
allSeconds[2]="02"
allSeconds[3]="03"
allSeconds[4]="04"
allSeconds[5]="05"
allSeconds[6]="06"
allSeconds[7]="07"
allSeconds[8]="08"
allSeconds[9]="09"
allSeconds[10]="10"
allSeconds[11]="11"
allSeconds[12]="12"
allSeconds[13]="13"
allSeconds[14]="14"
allSeconds[15]="15"
allSeconds[16]="16"
allSeconds[17]="17"
allSeconds[18]="18"
allSeconds[19]="19"
allSeconds[20]="20"
allSeconds[21]="21"
allSeconds[22]="22"
allSeconds[23]="23"
allSeconds[24]="24"
allSeconds[25]="25"
allSeconds[26]="26"
allSeconds[27]="27"
allSeconds[28]="28"
allSeconds[29]="29"
allSeconds[30]="30"
allSeconds[31]="31"
allSeconds[32]="32"
allSeconds[33]="33"
allSeconds[34]="34"
allSeconds[35]="35"
allSeconds[36]="36"
allSeconds[37]="37"
allSeconds[38]="38"
allSeconds[39]="39"
allSeconds[40]="40"
allSeconds[41]="41"
allSeconds[42]="42"
allSeconds[43]="43"
allSeconds[44]="44"
allSeconds[45]="45"
allSeconds[46]="46"
allSeconds[47]="47"
allSeconds[48]="48"
allSeconds[49]="49"
allSeconds[50]="50"
allSeconds[51]="51"
allSeconds[52]="52"
allSeconds[53]="53"
allSeconds[54]="54"
allSeconds[55]="55"
allSeconds[56]="56"
allSeconds[57]="57"
allSeconds[58]="58"
allSeconds[59]="59"
As you can see, not only did that take too long to write, but every value is exactly the same as its element number except for the first ten elements. Since loop variables are just numbers, we can use the variable to generate these values for us with proper construction.
For the first ten elements, we need to add a zero to the front of the loop variable for their corresponding element values since the first 10 seconds (0-9) of a digital clock are displayed that way. But for the element indices themselves, we only need to use the value of the loop variable. We'll start the counter at 0 and set the condition to be less than or equal to 9.
var allSeconds = new Array()
for (var i=0; i<=9; i++) {
allSeconds[i] = "0" + i
}
And wa-la, the first 10 elements of the allSeconds array are generated for us thanks to the incrementing value of the counter. To help clarify what is happening in the loop, visualize the i variable first as the number 0 as both the element number and element value, then 1, then 2, and so on up to 9.
Now on to the remaining 50. We'll start the counter at 10 by initializing the loop variable with a value of 10, then set the condition to be less than or equal to 59. The incremented value of the loop variable solely supplies both the element indices and their corresponding values.
for (var i=10; i<=59; i++) {
allSeconds[i] = i
}
There you have it. The loop has done the tedious work for us, and shortened the code substantially.
You might have noticed that in the manually written array as well as the first loop generated array, the values are coded as strings, but in the 2nd loop that generates the last 50 elements, the values are numbers. This is because in order to display the first 10 seconds in a digital clock fashion, a zero needed to be concatenated to the front of the numbers. When concatenating a string with a number, you end up with a string data type. So to keep the same visual convention in the manually written array, I just coded all the values as strings. In the loop generated array, I didn't bother because the values are the same whether they are presented as strings or numbers.
Another difference between the manually written and loop generated arrays is the optional length parameter declared in the array object constructer. If in the loop generated array, I had used the optional length parameter, the condition could have been constructed differently. By stating the length of the array, 60, the condition could be constructed like this:
var allSeconds = new Array(60)
for (var i=10; i<allSeconds.length; i++) {
allSeconds[i] = "0" + i
}
By declaring that there are 60 elements in the array, my condition could read, "as long as i is less than the length of the array, or less than 60". Notice it does not say, "less than or equal to 60", otherwise we'd end up with 61 seconds since the elements begin at zero.
Both ways are perfectly acceptable. Different scenarios as well as preference will dictate which technique you choose.
View the Source