Loops
while statement

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) statement

If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.

The condition test occurs before statement in the loop is executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.

To execute multiple statements, use a block statement ({ ... }) to group those statements.

Example:

The following while loop iterates as long as n is less than three:

var n = 0;
var x = 0;
                    
while (n < 3) {
    n++;
    x += n;
}

With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

do...while statement
let result = '';
let i = 0;

do {
    i++;
    result += i;
} while (i < 5);

console.log(result);    // 12345
for loop
for (i = 0; i < 5; i++)
console.log(i);


// for...in loop
const obj = {
    anubhav: 38,
    rohit: 45,
    aditya: 38,
    raj: 45
};

for (let a in obj) {
    console.log(a);     // returns a key value
    console.log(obj[a]);    // returns the value of key
}

   
// for...of loop
for (let a of "Anubhav") {
    console.log(a);
}

// A
// n
// u
// b
// h
// a
// v


const array1 = ['a', 'b', 'c'];

for (let element of array1) {
    console.log(element);
}