For Loop
Loops are used for iteration, i.e., repeating the execution of certain commands until the loop meets a certain condition. The for loop is the shortest form of a loop, and it must be passed three key parts:
- Variable initialization. Initialization is performed only once, before the execution of the for loop.
- Condition testing that returns true or false. If the condition is true, the code inside the loop continues to execute, otherwise, the loop ends. This part is iterated, i.e., it is executed after each step of the loop after changing the variable
- The variable change command is executed after each step and most often increases or decreases the counter
for (initialization; condition check; variable change) {
// commands to be executed until the loop condition returns true
}
In the following example, the variable inside the loop is set to a value of 1, the condition is set to <= 10, and the variable change command is set to increase the variable (increment) by 1 after each iteration or repetition.
<script type="text/javascript" >
var number;
document.write("Printing the first 10 numbers!" + "<br />");
// for loop
for(number = 1; number <= 10; number++) {
document.write("Value of variable <b>number</b> : " + number);
document.write("<br />");
}
</script>
The for loop takes the number variable and increases it by 1 until it reaches 10. After each increase, it outputs the number value and moves to a new line.
While loop
The while loop executes a block of code as long as the condition in the while loop is met. The while loop is used when the number of required iterations is not known.
Syntax:
while (condition) {
//statements
};
In the next example, it checks whether the variable 'number' is less than 11. If it is less, the block of code within the loop is executed and the variable 'number' is increased by 1 on the last line. When the variable value reaches 11, the loop will stop executing.
<script>
var number = 1;
while (number < 11) {
document.write("Value of variable <b>number</b>: " + number);
document.write("<br />");
number++;
}
</script>
Do/while loop
JavaScript offers another loop structure known as do...while. The formal syntax for this construct is as follows:
do {
//statements
} while (condition);
The difference between the while and do.. while loops is that in the do.. while loop, the commands are executed at least once before the condition is checked, while in the while loop this is not the case.
var number = 10;
do {
document.write("Value of variable <b>number</b>: " + number);
document.write("<br />");
number++;
} while (number < 10);
In the previous example, despite the condition not being met, the loop will still execute once, which would not be the case with a while loop.
For...in Loop
The for...in loop is primarily used for iterating over the enumerable properties of an object. This loop iterates over the keys of the object, allowing you to access the corresponding values within each iteration.
Syntax:
for (variable in object) {
// statements
}
Example:
let person = {
name: "Alice",
age: 25,
occupation: "Developer"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
In the above example, the for...in loop iterates through each key in the person object. The variable key takes on the value of each property name (or key) of person during each iteration, allowing the code to log the key and its corresponding value.
ForEach Method
The forEach method is an Array method that is used to execute a provided function once for each array element. It’s a part of modern JavaScript and provides a cleaner and more expressive syntax compared to traditional for loops for array iteration.
Syntax:
array.forEach(function(currentValue, index, arr), {
// statements
})
Example:
let colors = ["red", "green", "blue"];
colors.forEach(function(color, index) {
console.log(index + ": " + color);
});
In this example, forEach iterates over the colors array. For each iteration, it executes the provided function, passing in the current element (color) and its index (index). This way, the function logs each color and its index in the array.
Break and continue statements
Sometimes loops don't need to continue iterating through the rest of the values in the loop counter range. The break statement is then used to exit the loop. The break statement tells the JavaScript interpreter to exit the loop, and the script execution continues after the loop if it exists.
The break statement orders to exit the loop if a certain condition is met.
for(i = 1; i <= 20; i++){
// Block of code
if (i == 15) {
break;
}
}
The continue statement orders that, if the condition is met, move to the next step, i.e., increase the counter value and continue the loop from that value.
for(i = 1; i <= 20; i++){
if (i == 13) {
continue;
// Block of code
}
}
In the case of nested for loops, the break and continue statements refer to the for loop in whose current scope the conditional statement falls.