0
0
Javascriptprogramming~5 mins

Do–while loop in Javascript

Choose your learning style9 modes available
Introduction

A do-while loop helps you run a block of code at least once, then keep repeating it while a condition is true.

When you want to ask a question and repeat it until the answer is correct.
When you need to show a menu and keep asking for choices until the user wants to stop.
When you want to process data at least once before checking if more work is needed.
Syntax
Javascript
do {
  // code to run
} while (condition);

The code inside do always runs at least once before the condition is checked.

The while condition is checked after running the code block.

Examples
This prints numbers 1 to 3, increasing count each time.
Javascript
let count = 1;
do {
  console.log(count);
  count++;
} while (count <= 3);
This keeps asking the user to type 'yes' before stopping.
Javascript
let input;
do {
  input = prompt('Type yes to stop');
} while (input !== 'yes');
Sample Program

This program prints the number starting from 5 down to 1, counting down by one each time.

Javascript
let number = 5;
do {
  console.log(`Number is ${number}`);
  number--;
} while (number > 0);
OutputSuccess
Important Notes

Remember, the loop runs the code first, then checks the condition.

If the condition is false at the start, the code still runs once.

Summary

Do-while loops run code at least once before checking the condition.

Use them when you want to repeat something but must do it at least once.