Javascript “do…while” Loops: Pt.5

Dallas Bille
3 min readAug 9, 2019

--

Pt.1: Regular “For” Loops

Pt.2: “For…in” Loops

Pt.3: “For… of” Loops

Pt.4: “While” Loops

Alright! This is going to be the last of my series on Javascript loops. I wrote this series because I think it’s great to know how and when to use different Javascript tools.

About “Do…While” Loops

These loops execute a block of code one time before it hits our “while” boolean conditional. This ensures code is executed whether or not the conditional in the “while” loop evaluates to false.

Feel free to test out this logic with some console.log’s.

Ex.

do {
console.log("this code will print out even though our loop evaluates to false")
} while(2 + 2 == 5)
=> "this code will print out even though our loop evaluates to false"

Then it hits the false “while” condition and terminates the loop before one iteration.

But if we set a counter, we get a different result.

Ex.

let i = 0
do {
console.log("this code will print out 6 times")
} while(i++ < 5)
=> "this code will print out 6 times"
"this code will print out 6 times"
"this code will print out 6 times"
"this code will print out 6 times"
"this code will print out 6 times"
"this code will print out 6 times"

I have been doing this for a year and have yet to find a practical reason to use a “do…while” loop. So I will get into some theoretical scenarios that should help illustrate the concept of the “do…while” loop.

Scenario:

I just came up with my own example to show how you could use a “do…while” loop to perform a task. It’s a super simple algorithm style question that you must solve using a “do…while” loop.

Write a function nonConsecutiveNames(), that prints out a list of names. If the next name is equal to the one most recently printed, then you terminate the loop, so that the same name does not print out consecutively.

Ex.

let names = ["Geoff","Glenda","Geoff","Tom","Geoff","Patsy","Patsy","Clark"]nonConsecutiveNames(names)
=> "Geoff"
"Glenda"
"Geoff"
"Tom"
"Geoff"
"Patsy"

Try it out. This is the first algorithm I have come up with, so it should be pretty easy.

Okay here’s the answer.

let names = ["Geoff","Glenda","Geoff","Tom","Geoff","Patsy","Patsy","Clark"]function noNameRepeat(array){
let i = 0
do {
console.log(array[i]);
i++
} while(array[i] != array[i-1])
}
noNameRepeat(names)

Explanation:

We know we need to set a counter to increment so we can keep track of the array indexes and loop through the array. We also know the first name can be printed automatically, so our “while” conditional reads, “if the current element is the same as the element we have previously printed, terminate the loop”. So if there are consecutive names, it prints the first one, and terminates before the second is printed.

Well. That’s it! If this series helped in anyway I’ll be satisfied. Now I need to ride one of these.

Resources:

MDN

W3Schools

--

--

Dallas Bille

Full Stack Web Developer, Adventurer, Soccer Player/Coach