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 Basics (Retired) Making Decisions with Conditional Statements Add a Final Else Clause

Why 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?

script.js
var isAdmin = false;
var isStudent = false;

if ( isAdmin ) {
    alert('Welcome administrator')
} else if (isStudent) {
    alert('Welcome student')
} else {
  alert('Who are you?')
}
index.html
<!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>

You 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:

if ( isAdmin ) {
    alert('Welcome administrator');
} else if (isStudent) {
    alert('Welcome student');
} else {
  alert('Who are you?');
}

2 Answers

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

When 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.

That is what I assumed, but I wanted to make sure. Thanks a lot, Ryan!!