DEV Community

loading...
Cover image for JavaScript Made Easy: Part 13

JavaScript Made Easy: Part 13

dtetreau profile image David Tetreau ・2 min read

For the last several posts we have been talking about loops. We went over the for loop, the nested for loop, the for/in loop, and the while loop. For Part 13, we will talk about our final loop. Open up your repl and code along!

The Do/While loop

The do/while loop executes a block of code before it ever checks conditions. Then, after the code block is executed, there will be a conditional statement which is checked. If the condition is true, it then repeats the loop as long as the condition remains true. The loop ends when the condition evaluates to false. The useful thing about do/while loops is that they will always execute the code at least once. If this is something that you are trying to accomplish with your program, the do/while loop is definitely something to keep in mind. The syntax for the do/while loop is as follows:


do {
  //statements
} while (condition);

Enter fullscreen mode Exit fullscreen mode

As you can see, the loop starts with the keyword "do". Then, inside the code block (inside the brackets), there are statements which are run. Each program will have a varying amount of statements depending on what it is trying to accomplish. As previously stated, these statements are always run at least once. Then, there is the keyword "while" accompanied by a conditional statement.


let i = 0;

do {
 console.log("The code ran");
 i++;
} while (i < 20);

Enter fullscreen mode Exit fullscreen mode

This loop will log "the code ran" to the console 20 times before the conditional is no longer true. If you were to change the conditional to the one listed below it would only run once:


let i = 0;

do {
 console.log("The code ran");
 i++;
} while (i === 0);

Enter fullscreen mode Exit fullscreen mode

Notice that the code runs once but stops at the conditional. If we did not increment the variable "i" in the loop, there would be an infinite loop. However, since "i" is incremented in the example, the loop stops when the condition is checked because "i" is no longer equal to 0.

Take some time to make your own do/while loops. What kind of programs would you want to use the do/while loops in? Try to incorporate a do/while loop inside of a function and call the function.

Here is a useful link access more information on loops from freecodecamp. The information there includes one loop we did not discuss, the for/of loop.

I hope you have enjoyed this post! Please check out the entire "JavaScript Made Easy" series by David Tetreau. There will be a new post daily.

Discussion (0)

Forem Open with the Forem app