A lot of times you want to loop through data and perform some action a certain number of times. When the number of iterations is already known, you can use the for loop.
Syntax:
for (initialization; condition; updation) { // code }
Example:
var num = 123; // num should be a three-digit number var digits = 3, sum = 0, n = num; for (var i = 0; i < digits; i++) { sum += (n % 10); n = Math.floor(n / 10); } console.log("Sum of the digits of " + num + " = " + sum);
Output:
"Sum of the digits of 123 = 6"
Let’s see the code described above running to gain a deeper understanding of the "for loop".
So you just learnt about the for loop and how a while loop can we converted into a for loop.
A for loop is different from a while loop for you can initialize a variable as a counter (or iterator) and execute the code written inside the body of the loop for a certain number of times.
Do you remember the break statement that we used previously in the switch..case statements? As you learnt previously, it breaks out of the condition. Break statement escapes from the curly braces that are enclosing it and the control goes to the next command after the curly braces. Let's find out how the break statement works in loops.
break:
A break statement is used to break away or terminate the current loop. Whenever and wherever a break statement is specified, it will terminate the current loop and then move onto the next valid statement outside of that loop.
continue:
continue is also an interesting statement, it tells the loop to skip the current iteration and move on to the next iteration of the loop.
So, in short, the break statement tells the program to terminate the loop entirely and come out of the entire loop, whereas the continue keyword tells the program to just skip the current iteration but the rest of the iterations still continue to occur.