DEV Community

Madhavan G
Madhavan G

Posted on

Basic About looping and While Loop in Javascript

Basic About looping and While Loop in Javascript

javascript

programming

beginners

tutorial

LOOPING:
Looping means repeating a block of code multiple times.

SOME EXAMPLE PROGRAM FOR LOOPING:

  1. Print 1 2 3 4 5 ?

let i = 1;

while (i <= 5) {
console.log(i);
i++;
}
OUTPUT:
1
2
3
4
5

Step-by-step Explanation:
*let i = 1;
We create a variable i and start it at 1
*while (i <= 5)
The loop runs as long as i is less than or equal to 5
*console.log(i);
Prints the current value of i
*i++;
Increases i by 1 after each loop

How it runs:

i = 1 → print 1
i = 2 → print 2
i = 3 → print 3
i = 4 → print 4
i = 5 → print 5
i = 6 → stop ❌

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:

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.

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

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

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

Top comments (0)