Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    3Topics
    |
    3 Quizzes
Lesson 7, Topic 7
In Progress

JavaScript: Do…While Statements

Yasin Cakal 23 Nov 2021
Lesson Progress
0% Complete

In some cases, you’ll want a piece of code to run at least once before looping based on a certain condition. The do…while statement is used in this case.

A do…while statement tells the computer to perform a task once and then repeat it until the condition is no longer met. A do…while statement has the following syntax:

let counter = '';
let i = 0;
 
do {
  counter = counter + i;
  i++;
} while (i <= 5);
console.log(counter);

//Output: 012345

In this case, the code block modifies the counter variable by appending the i variable’s string form to it. The code block following the do keyword is first executed once. The situation is then assessed. The block will be executed again if the condition evaluates to true. When the condition evaluates to false, the looping stops.

The while and do…while loops are not the same! Do…while, unlike the while loop, will run at least once regardless of whether the condition evaluates to true.

const firstMessage = 'Do while statement';
const secondMessage = 'While loop statement'; 
 
// do while with stopping condition == false
do {
 console.log(firstMessage)
} while (true === false);
 
//while loop with stopping condition == false
while (true === false){
  console.log(secondMessage)
};

//Output:  Do while statement

Responses

Leave a Reply

%d bloggers like this: