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 Boolean Values

Keith Greatz
Keith Greatz
4,377 Points

Semi colon not required?

Hi, I remember Dave saying not to put ; at the end of any statements when using conditionals. I tested the code without ; and it works.

Is it just a matter of preference as whether to put in the ; or will I run into issues later on If i develop this habit?.

correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
console.log(randomNumber);
var guess = prompt('I am thinking of a number between 1 and 6. What is it?')
if (parseInt(guess) === randomNumber ) {
  document.write('<p>You guessed the number!</p>')
 correctGuess= true;
}

if (correctGuess) {
  document.write ('<p> You guessed the number!</p>')
} else {
  document.write("<p>Sorry. The number was " + randomNumber + ".</p>")
}

Thanks

Keiffy101

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Keith,

That's probably not what Dave meant when he said not to put semicolons on the end of statements when using conditionals.

if (parseInt(guess) === randomNumber ) { //Dave probably means don't put one here!
  document.write('<p>You guessed the number!</p>')  //You should always put one here!
 correctGuess= true;
}

You should always use semicolons at the end of your actual statements. The statement you put inside a conditional check doesn't count.

In most cases, your JS will work just fine without semicolons, but there are instances where you'll run into problems. There's a rather contrived example in this StackExchange post (see the second answer) of where it can cause bugs.

Regardless, it's a best practice, so keep those semicolons around!

Cheers,

-Greg