For Loop

for (initialization; condition; finalExpression) {
  // Code to be executed in each iteration
}

for(let i = 0; i < 10; i++) {
	console.log(i);
}

Explaining the flow, first i = 0, then it checks the condition, if yes, then it runs the main body and finally the increment. and it repeats until the condition is dissatisfied.

Task -

  1. Print numbers from 20 to 1.
  2. Print odd numbers from 1 to 20
  3. Print hello world 1, hello world 2 and so on upto hello world 30.

While Loop

while (condition) {
  // code block to be executed
}

let i = 1;
while (i <= 10) {
    console.log(i);
    i++;
}

Task - Do the same for while loop

Do while Loop

do {
  // code block to be executed
}
while (condition);

let i = 1;
do {
    console.log(i);
    i++;
} while (i <= 10);

No matter the condition match or not, do while loop runs at least one time.

What is break ?

It is used to jump out of a loop.

for(let i = 1; i <= 10; i++) {
    if(i == 6) {
        break;
    }
    console.log(i);
}

What is Continue ?

It skips one loop iteration

for(let i = 1; i <= 10; i++) {
    if(i == 6) {
        continue;
    }
    console.log(i);
}

Nested Loop Problems