Ad

JavaScript while loop (with example)

  

JavaScript while loop 




While statement create a loop ()is executed while a condition is true .

 while loop run the condition is the true.

In JavaScript, a while loop is used to carry out repetitive operations by running a block of code repeatedly as long as a given condition is met.

 The code inside the loop is run once the loop has evaluated the condition and found that it is true.

 The condition is verified once again following each execution of the loop's code block. 

The loop continues in this manner until the condition evaluates to false, at which time it breaks and the code that comes after the loop executes.

Syntax :- 

while (condition check)


{


code executed


}


Code Explain :-

     à®ƒ While loop  use the codition inside ( ).

    à®ƒ  while loop  condition  TRUE then code { } executed.

    à®ƒ while loop code evaluate again.

    ஃ This condition  FALSE then loop terminates.


FlowChart  

           

while loop Example


Q. Display Number of 1 to 15 


let num =1;
while (num <=15)
{
  console.log(num);
  num++;
}

Explain :-


 num initialized to 1
 while loop continues
   count is less than equal(num<=15)
   console.log(num)
   After num ++ increment value 1 each iteration.

Output :- 


2] while loop Example

Q. Display Number from 1 to 4


let x=1;
while(x<5)
{
  console.log(x);
  x+=1;
}

Explain :-


  initialized variable 1

while loop continues count  less  (x<5)
console.log(x)
  x is increment by 1

Output :-


3]while loop Example

count number in while loop


let count_number=1;
while(count_number<5)
{
    console.log(count_number);
    count_number++;
}

1]  let count_number = 1 
2] count_number<5 loop runs while loop.
3] less than 5 count_number = 1 
4] console,log(count_number = 1 )
5] print current value and count_number ++ increment value by 1 each time.
6] count_number  reaches 5 value the condition false 
7] than loop exits

Output :-



Related Post :-

No comments

Powered by Blogger.