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 trialmctheta
3,709 PointsWhy do we not use a semi-colon at the of a command within an if-else statement?
If the codeblock within the if statement has several commands across multiple lines, doesn't it need the semi-colon to know when the end of each command is? or is the semi-colon not needed if there is only a single command?
var isAdmin = false;
var isStudent = false;
if ( isAdmin ) {
alert('Welcome administrator')
} else if (isStudent) {
alert('Welcome student')
} else {
alert('Who are you?')
}
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JavaScript Basics</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
2 Answers
Ryan Field
Courses Plus Student 21,242 PointsWhen the code inside of an if/else statement is a single line of code, such as return false
or alert('hello')
, the comma is not required.
I find, however, that it's better practice for me to always use semicolons, even if not required, as it makes reading and maintaining my code that much easier.
mctheta
3,709 PointsThat is what I assumed, but I wanted to make sure. Thanks a lot, Ryan!!
Matt Brock
28,330 PointsMatt Brock
28,330 PointsYou need a semicolon after a command in JavaScript or the parser won't know when the command is finished. Your variable declarations are correct. A conditional does not require a semicolon after the closing curly bracket since the commands are contained inside. It would give a syntax error. You do, however, need to have a semicolon at the end of every command line inside the if statement: