JavaScript Loops (Repeat a sequence of statements)
In this tutorial you will learn javascript loops and their usage.
Loops execute a code block a certain number of times, as long as a certain condition is met. We can use loops to do many things, such as repeating operations a number of times and iterating over data sets, arrays, and objects.
JavaScript now supports five different types of loops:
- while — loops through a block of code as long as the condition specified evaluates to true.
- do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
- for — loops through a block of code until the counter reaches a specified number.
- for…in — loops through the properties of an object.
- for…of — loops over iterable objects such as arrays, strings, etc.
while loops
A while loop executes a certain block of code as long as an expression evaluates to true. The snippet below demonstrates.
The syntax of the while loop:
while (condition) { // code that gets executed as long as the condition is true }
The while loop will only be executed as long as the condition is true, so if the condition is false to begin with, the code inside will be skipped. Here is a very simple example of a while loop printing the numbers 0 to 10 (excluding 10): Try It
let i = 0; while (i < 10) { document.write("<p>The number is " + i + "</p>"); i++; }
Note: Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as infinite loop. A common mistake is to forget to increment the counter variable (variable i in our case).
do while loops
The do-while loop is a specialized form of while loop where the code block is executed at least once and then the condition is checked to determine further execution. If the condition resolves to true, code block is executed again.
The syntax of the do-while loop:
do { // code to be executed if the condition is true } while (condition);
Here is a very simple example of a do-while loop printing the numbers 0 to 10 (excluding 10):
var i = 1; do { document.write("<p>The number is " + i + "</p>"); i++; } while(i <= 10);
let number; do { number = prompt("Please enter a number between 0 and 100: "); } while (!(number >= 0 && number < 100));
for loops
The for loop is the simplest of all and very comprehensive to write. The for loops take an initial value, termination condition and increment/decrement condition as input. The initial value is used only once for initialization purposes. The termination condition is tested, and the block is executed. Once the block is executed, the increment/decrement condition is evaluated to update the value of counter. The test condition is checked again, and the code is executed if the counter satisfies the condition. This way the loop continues to execute until the counter value fails to meet the criteria or the termination condition is met.
The syntax of using for loop is given as:
for (initial value; termination condition; statement) { //block of statements to execute }
Three important parts of for loop:
- The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
- The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
- The iteration statement where you can increase or decrease your counter.
for (i = 1; i <= 10; i++) { document.write ("value of i is"+i); }
break and continue
break and continue are two keywords that we can use to control the flow of execution of the loop. break will stop the loop and move on to the code below the loop. continue will stop the current iteration and move back to the top of the loop, checking the condition (or in the case of a for loop, performing the statement and then checking the condition).
break
We have already seen break in the switch statement. When break was executed, the switch statement ended. This is not very different when it comes to loops: when the break statement is executed, the loop will end, even when the condition is still true.
Here is a simple example to demonstrate how break works:
for (let i = 0; i &l; 10; i++) { document.write(i); if (i === 4) { break; } }
let names = ["Gopal", "Rama", "Raghav", "Keshav", "Madhav"]; for (let i = 0; i < names.length; i++){ if (names[i] === "Raghav") { document.write (names[i] + "found at array location: ", i); break; } }
continue
break can be used to quit the loop, and continue can be used to move on to the next iteration of the loop. It quits the current iteration and moves back up to check the condition and start a new iteration.
let i = 1; while (i < 50) { i++; if (i % 2 === 0){ continue; } document.writeln(i); }
while(true) { var grade=eval(prompt("What was your total marks? ","")); if (grade < 0 || grade > 100) { alert("Illegal choice!"); continue; // Go back to the top of the loop } if(grade > 89 && grade < 101){ alert("Wow! You got an A!"); } else if (grade > 79 && grade < 90){ alert("You got a B"); } else if (grade > 69 && grade < 80){ alert("You got a C"); } else if (grade > 59 && grade < 70){ alert("You got a D"); } else { alert("Study well. You Failed."); } answer=prompt("Do you want to enter another grade?",""); if(answer != "yes"){ break; // Break out of the loop } }
Nested Loops:
A loop within a loop is a nested loop. A common use for nested loops is to display data in rows and columns. One loop handles the rows and the other handles the columns. The outside loop is initialized and tested, the inside loop then iterates completely through all of its cycles, and the outside loop starts again where it left off. The inside loop moves faster than the outside loop. Loops can be nested as deeply as you wish, but there are times when it is necessary to terminate the loop owing to some condition.
var str = "@"; for (var row = 0; row < 6; row++){ for (var col=0; col < row; col++){ document.write(str); } document.write("<br>"); }
for(let i=1; i<=10; i++){ document.writeln("<b>"+"Multiplication Table of " + i + "</b>
"); for(let j=1; j<=10; j++){ document.writeln(i + "x" + j + "=" + i*j); document.writeln("<br>"); } document.writeln("<br>"); }