Submodule 7.2: Loops
for loop
For loops are the most common looping in JavaScript. Typically, we use it when we know the number of iterations we need: a fixed number (count to ten) or the length of a data structure.
The for loop has the following syntax:
for (initial expression; test to run; increment) {
code block to be executed
}
Example 1
/*let's count from 1 to 5*/
for (var index = 1; index <= 5; index++){
console.log(index);
}
In this example, we set our three expressions in the for loop.
- the initial expression: this is executed once before the loop runs, and typically sets the initial condition for the counter: in this case, setting index equal to 1
- the test to run before each iteration over the loop: if this evaluates to true, the loop will continue
- executed after each iteration through the loop. In this case, we use it to increment index to the next value.
Tip: Copy the above piece of code and paste it directly into the console, to see how it works.
Example 2
In this example, we create an array of colors and use the loop to iterate over the array and output its contents to the console.
/* remember that arrays start at zero
so we will loop from 0 to the length of the array*/
var color = ["red", "green", "blue"];
for (var i = 0; i < color.length; i++){
console.log(color[i]);
}
Tip: Copy the above piece of code and paste it directly into the console, to see how it works.
For more information: https://www.w3schools.com/js/js_loop_for.asp
Exercise
Loop through the integers from 1 to 100 and write each to the console only if it is odd (check if the remainder - % - after the division of the integer by 2, is 1). Work directly in your console.
for(var j = 0; j < 100; j++ ){
if (j % 2 == 1){
console.log(j)
};
};