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 trialJelena Bacic
996 PointsWhile 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
ishakahmed
11,359 PointsIn short, yes, use a semicolon @ the end of do-while statements.
do {
// insert code here
} while ( true );
Luc de Brouwer
Full Stack JavaScript Techdegree Student 17,939 PointsNo 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
Full Stack JavaScript Techdegree Student 11,256 PointsLuc, 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
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