Hai everyone. Do you know what is While loop in JavaScript ? …oh, Now we are going to learn what is While loop for better understanding we take an example !
Just in simple words
Repeatedly Excutes statement as long as a given condition is True
The situation when programming is needed to perform a certain action again, again Until certain condition
syntax :
while(Expression needed to be executed){
The Statement that has to be executed, Until the above expression holds the value to false
}
Here firstly the while loop evaluates the condition inside(),
If the condition evaluates to True the code inside { } is Executed
Example
let count = 1; // here its Initial value is starting from 1
while(count<=6){ //condition is from initial to until 6
console.log(count);
count++ // the count will be incremented
}
output : 1 2 3 4 5 6
- Firstly, The count is Initialized to 1
- The loop runs as long as count is greater than less than and equal to 6
- Inside the loop console.log(count) outputs the current value of count
- After each iteration , count is incremented by 1. (count++)
While loop by taking user input
let num = 0 ,sum=0 ;
while(num >=0){
sum = num+sum;
num = parseInt(prompt("enter a number: "));
console.log(`the sum is ${sum}`);
}
In the above program prompts is used to the user to enter a number
- The conditon of loop is if the num were greater than zero only it will take. when we give negative i won’t allow
- The JavaScript prompts() only takes input as string , parseInt() is used to convert the input to number
As long as we enter a positive number the While loop adds them up and ask us to enter more numbers