DEV Community

Deva I
Deva I

Posted on

Basic About While Loop in Javascript

WHILE LOOP:
✓ While loop is a control flow statement that is used to execute a code repeatedly when the specified condition is true.

✓ If the condition is false then the code is stop and breaks the loop.

✓ If the condition never becomes false then the code will runs repeatedly.This is called infinite loop.

SOME EXAMPLE PROGRAM FOR WHILE LOOP:
1.Print 1 2 3?

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

✓First take the initial value
i = 1;

✓Then give the condition , our final value is 3, so take the value less than 3.

✓ Print the value of i.

✓Then increment the value of i.

WORKING:

  1. First the initial value starts 1

2.Then check the condition it's executes when the condition evaluates true.

3.Then prints the initial value 1
i is 1 (1 <= 3 is true). Prints 1, then i becomes 2.

4.i is 2 (2 <= 3 is true). Prints 2, then i becomes 3.

5.i is 3 (3 <= 3 is true). Prints 3, then i becomes 4.

6.Then checks i is 4. But 4 <= 3 is false,so the loop will stop.

2.Print 3 2 1?

let i = 3;
While(i >= 1)
{
Console.log(i);
i--;
}

3.print 1 3 5 7 9?

4.Print 3 6 9 12 15?

Print 1 4 9 16 25?

 .

Top comments (0)