When it comes to programming, a for loop acts as an iterator that functions like a counter or stepping progression. If you need to repeat a task a certain number of times, then a for loop is your go-to tool. However, understanding how to effectively utilize for loops can be challenging for beginners.
Let's explore a simple example to illustrate this concept:
Irrelevant Example:
// Increment the value of x and display the new value in the console 20 times.
var x = 6;
for(var i = 0; i < 20; i++) {
x++;
console.log("Value of x: " + x);
}
If we analyze the code closely, it follows a logical sequence. You initialize an iteration variable i
, specify when to stop (i < 20
...stop when i = 20), and determine how to progress with each iteration (i++
or i + 1).
The loop begins when i = 0
, increments the value of x
by 1 (x++), resulting in x = 7. This process continues for each iteration until i = 20
, after which the loop exits, and the program proceeds. By completing the loop, we have increased x
by 1 twenty times. Initially set at 6, x
now equals 26.
Relevant Example:
// Print out each element in an array of length 10
for (var i = 0; i < cookiearray.length; i++){
console.log(cookiearray[i]);
}
In this scenario, the for
loop operates similarly, iterating until i
matches the length (number of elements) of the array (in this case, 10). When i = 0
, our code displays the element located at index cookiearray[0]
. As i
increases, subsequent elements in the array are printed.
One potential point of confusion in the example involves the split function, which returns an array. For instance, consider this line:
name = cookiearray[i].split('=')[0];
This statement directs the program to assign the first element of the array generated from splitting the string at position i
within the cookiearray.
Assuming cookiearray[0] = "Hello=World"
, when i = 0
, the code splits "Hello=World" into a new array where the 0th element is "Hello," which becomes the value stored in the local variable name
. Therefore, name = "Hello"
.