While writing a script, there may be a situation when you need to perform some action over and over again. In such a situation, you would need to write loop statements to minimize the number of lines of code. For example, if you want to display 'hello' 10 times, then write one statement and repeat it using a loop.
Types of Loops: for, while, do while
Syntax: for loop:
for(start; condition; step) { // statements... }
for(let i=1;i<=10;i++) { console.log("The number is " + i); }
let i=1; for(;i<=10;i++) { console.log("The number is " + i); }
let i=1; for(;i<=10;) { console.log("The number is " + i++); }
for(;true;) { console.log("Infinite loop); }
for(;;) { console.log("Infinite loop"); }
Syntax: While loop:
let i=1; while (i<=10) { console.log("The number is " + i); i++; }
Syntax: Do While loop:
let i=1; do { console.log("The number is " + i); i++; }while (i <= 10);
A Nested loop is a loop inside another loop.
for(let i=1;i<=5;i++) { for(let j=1;j<=5;j++) { console.log("Hello"); //printed 5*5=25 times } }
Similarly, you can use nested while and nested do-while loops.
If we want to stop the execution of a loop, then use the break statement. In short, a break terminates a loop and passes control to the next line of a loop.
for(let i=1;i<=10;i++) { console.log("The number is " + i); break; } // The number is 1 (only 1 time)
for(let i=1;i<=5;i++) { console.log("The number is "+i); if(i==3) break; } // The number is 1 // The number is 2 // The number is 3
Break used in nested loop:
for(let i=1;i<=5;i++) { for(let j=1;j<=5;j++) { console.log('i='+i+' j='+j); break; } } //i=1 j=1 //i=2 j=1 //i=3 j=1 //i=4 j=1 //i=5 j=1
Label loop for Break
outer: for(let i=1;i<=5;i++) { inner: for(let j=1;j<=5;j++) { console.log('i='+i+' j='+j); break outer; //breaks the i for loop } } //i=1 j=1 //i=1 j=2 //i=1 j=3 //i=1 j=4 //i=1 j=5
The continue statement is used to skip the statement. In other words, it stops the current iteration of a loop, instead of the whole loop.
for(let i=1;i<=5;i++) { if(i==3) continue; console.log("The number is "+i); } // The number is 1 // The number is 2 // The number is 4 // The number is 5
Ad: