Javascript - while vs do while loop
Osama Soliman
Geek Software Engineer ?? | JavaScript | Angular | Ionic | NestJS | and Much More... Let's Get In Touch
Have You ever wondered what is the difference between these two loops?
Here's the answer:
while (numOfCustomers > 0){
console.log("How can I help you ?");
// Help The Customers
numOfCustomers = numOfCustomers - 1;
}
//vs
do{
console.log("How can I help you ?");
// Help The Customers
numOfCustomers = numOfCustomers - 1;
}while(numOfCustomers >1)
The only difference between these loops is whether the conditional is tested before the first iteration (while) or after the first iteration (do .. while).
In either form, if the conditional test as false the next iteration will not run that means if the condition is initially false a (while) loop will never run but a (do..while) loop will run just the first time.