Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

While and doWhile loop. Use a semicolon or not?

So.. Simple question: Do I use a semicolon at the end of the loop(s) or not? And why?

Thanks!

2 Answers

In short, yes, use a semicolon @ the end of do-while statements.

do { 
// insert code here
} while ( true );
Luc de Brouwer
seal-mask
.a{fill-rule:evenodd;}techdegree
Luc de Brouwer
Full Stack JavaScript Techdegree Student 17,939 Points

No you don't. A loop knows where it ends because of its curly braces. Sometimes however in OOP you will see that they put semicolons behind a curly brace.

Be cautious with loops, especially with while loops if you don't implement a way to get out of the loop

weo3
seal-mask
.a{fill-rule:evenodd;}techdegree
weo3
Full Stack JavaScript Techdegree Student 11,256 Points

Luc, it seems you missed the specificity of Jelena's query, which is about do...while loops. Isha was correct.

Jelena, you actually have two different scenarios, and so you actually have two different answers for your whole question.

The first, with a while statement, the answer is no, you do not - much like Luc has said, you do not need semicolons after braces in this case.

while ( expression is true )  {
  // do something
}

However, with the do/while statement, yes, you do need a semicolon.

do {
  // something
} while ( expression is true);

For valid reference, always go to MDN's JavaScript site.

while - using while statement

do/while - using the do...while statement

Hope that clarifies everything for you.

Luc de Brouwer
seal-mask
.a{fill-rule:evenodd;}techdegree
Luc de Brouwer
Full Stack JavaScript Techdegree Student 17,939 Points

@weo3 you are perfectly right in this. I would like to add w3schools for an easier reference to get into javascript things. Thanks for taking time to answer on both sides of the related question