Why Loops?

"Looping" is something every modern programming language allows the author to make use of. It refers to the method by which you apply a single section of code to a set of variables or objects collected together within one array. This can be a list of a single data type, like numbers or words, or it can be a list of objects with their own internal properties and variables.

This is extremely similar to the way in which we can save time and space by condensing repeated actions into functions. With loops we can repeat the same actions or functions, but now with only having to even invoke function but once, for all the data it nees to affect.

Loop Syntax

Let's look at how an actual loop is written. The structure will not vary much between needs. The only time you'll modify the loop structure is if you need to loop backwards (discussed below) or if for some reason you need to look at only a section of a particular array.

Examine the following structure and note two things. 1. how it begins with the keyword "for", and 2. how the code within the parethesis comes in three main parts.


<script>

for (i = 0; i < array_name.length; i++){
	// Code to execute
}

</script>

Now let's consider each part one at a time...

for (i = 0; i < array_name.length; i++){ // Code to execute }
The keyword "for" simply denotes the beginning of a loop. It is not unlike an "if" statement in how it is a standard keyword that needs to adhere to a strict format. Loops always start with the word "for", followed by parenthesis with the looping instructions, followed by curly brackets encasing the code to be run.
for (i = 0; i < array_name.length; i++){ // Code to execute }
A loop needs to "count" over entries in any given array. The initial counting position is typically written as "i = 0"; This means we are making what is essentially a temporary integer variable which is set to "0" to start.
The position declaration always ends with a ";" as if it were an individual line of code. This will separate it from the other sections.
for (i = 0; i < array_name.length; i++){ // Code to execute }
In the second section we state the question that will be asked upon every iteration of this loop to decide if it should continue. Here you see the traditional statement that can be read as "if 'i' is still less than the length of the array".
This is the part that you will always change as "array_name" needs to reference the array that you are actually looping over.
for (i = 0; i < array_name.length; i++){ // Code to execute }
The third part of the "for" statement decides what will happen at the end of each loop should the condition of the second part be found true. In the traditional "for" loop it simply increments the counting variable. When "i" is increased by one we will be able to use "i" within the encapsulated code to reference that position of the array. If "i" is incremented past the length of the array then the for loop will know to stop running since it needs to be less than the length of the array (as dicated by the part two of the statement).

Of course the "Code to execute" section of each of these examples depends entirely on the purpose of the program. What's important to realize is that by making use of the "i" variable declared in the first line of the "for" loop we can access different entries of the array.

Note: The letter "i" is incidental. Any letter can be chosen as long as it is constant throughout the code of the loop.

Traversing Loops

For instance. Let's look at some code where we loop over a short array of words and count the number of occurrences of a particular word within that array...


<script>

var fruits = ["apple", "orange", "watermelon", "orange", "permisson", "pumpkin", "banana", "orange"];

var result = 0;

for (i = 0; i < fruits.length; i++){
	if( fruits[i] == "orange"){
    	result += 1;
    }
}

console.log( result ); 		// returns "3";

</script>

In this case, as is noted in the comment, the final result of the "result" variable will be the number "3". This is because for every iteration of the loop the code within the loop is checking if the current word is "orange". If it is then the "result" variable is increased by one. The important part to consider is the reference "fruits[i]". This references a particular position within the array but instead of the author having to write an exact number within the square brackets we use the parameter "i" instead.

The for loop will replace "i" with the current value of the counting variable automatically for as long as "i" is less than the length of the array.

This means that it will check "fruits[0]", "fruits[1]", "fruits[2]", and so on, and so on, and so on...

Just remember that arrays start with "0". This is why the use "less than" the total length of the array instead of "less than or equal to". To use a "<=" sign would produce one more check than there are entries in the array since we are counting "0" to begin with.

Loop Breaking

Typically running through an entire loop is not a taxing operation. But if you are looking for a particular point or conclusion to a loop then you can break out of a loop, and thereby not waste any more processing power, via the use of the "Break" keyword.

Let's repeat the code found above, but with one simple change. See if you can find it.


<script>

var fruits = ["apple", "orange", "watermelon", "orange", "permisson", "pumpkin", "banana", "orange"];

var result = 0;

for (i = 0; i < fruits.length; i++){
	if( fruits[i] == "orange"){
    	result += 1;
        break;
    }
}

console.log( result ); 		// returns "1";

</script>

It's a very minute change, but all we've done is add a single line to the if statement, right in the middle of the for loop.

In this case, should you run this code, you'll find that the "result" variable ends with value of "1" instead of the previous "3". Why is this? Because since in this case we wanted to demonstrate only finding the first occurrence of the word "orange" we simply inserted the keyword "break" within the if statement (ending with a semicolon of course).

This tells the loop to cease iterating over every entry in the list - even if it has not yet fullfilled the condition of the loop. Once "break" is invoked the loop stops altogether without checking the remainder of the array.

Because of this we only have a count of "1" in results because the loop checked the first entry, "apple", and did nothing, then checked the second entry "orange", added to the total count of "result" and then ceased to run.

There are many reasons you might want to do this. You could be looking for a single occurrence (such as checking which button your cursor is over), you could doing a math problem that only needs a certain amount of accuracy before ceasing calculations (such as with a square root), or you might be filling another array of limited size. Whatever the reason it is a good thing to always keep in mind to help cut down on waste.