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 trialMagan Tyson
1,285 PointsMy code works when I remove the ";".
Good day!
Through out the courses I have been taking, I remember being told "functions don't utilize semi-colons" and "if else (else if ) statements don't use semi-colons".
However when I follow along the instructor uses them. When I try to run the code I get an error message.
Uncaught SyntaxError: expected expression, got keyword 'else' multiple-returns.js:5:3
When I remove the semi-colons from both the function and the if else statement the code runs as it is intended.
Why? I understand that there are ways, as I learn to code, to make things work with out understanding why. I am trying to be very cautious not to be content when this happens. I want to comprehend as I go.
Also, am I doing something wrong? Is there a best practice I may be missing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Functions</title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<main>
<input type="text" id="info">
</main>
<script src="js/multiple-returns.js"></script>
</body>
</html>
function isFieldEmpty() {
const field = document.querySelector('#info');
if (!field.value); {
return true;
} else {
return false;
}
}
const fieldTest = isFieldEmpty();
if (fieldTest) {
alert('Please provide your information.');
}
1 Answer
Steven Parker
231,274 PointsA semicolon ends a statement, so if you write if (!field.value); {
the "if" statement ends at the semicolon without any code being controlled by the test. The following brace no longer encloses a conditional block, it now begins a code block that will run in all cases. But you should get a syntax error at the "else" because it has no matching "if".
On the other hand, you can use semicolons in your if or ifโฆelse when your conditional code is one single statement instead of a code block. For example, the following would be valid:
if (!field.value) return true;
else return false;
Although a much easier and more efficient way to do this is without any conditional at all:
return !field.value;