DEV Community

Cover image for JavaScript: Do While Loop
12 7

JavaScript: Do While Loop

We learned about while loops in the previous blog post. Loops allow us to repeat the same action multiple times.

The key difference between a while and a do-while loop is that the former evaluates the end condition before running the body. In contrast, the latter evaluate it at the end of body execution.

Why does this matter?

While while-loop is evaluating it in the beginning, if the condition is false, the body does not get executed. The do-while ensures body execution once because of the expression evaluation at the end.

A while loop looks like

while(condition) { // If condition is false to start with, this loop will never run.
    // loop body
    // counter++
}

A do-while loop looks like

do {
    statement // This statement will execute at least once before the execution of the condition below!
}
while (condition);

Example of a do while loop:

let i = 0;
do {
    console.log(i); // 0, by the time condition gets evaluated this variable gets printed to the console.
} while (i != 0);

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
yusufcodes profile image
yusufcodes β€’

Nice little post on do-while

Collapse
 
bhagatparwinder profile image
Parwinder πŸ‘¨πŸ»β€πŸ’» β€’

Thank you! When I’m having a productive day I write long detailed posts about Observables and Closures and what not. When it’s a day to relax, I whip out a small post πŸ˜‰

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay