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
Jonathan Grieve
Treehouse Moderator 91,254 PointsQuick question on Javascript Conditionals
I remember in the Javascript Basics course David talks about in conditions you have to have one if statement and one else statement.
But in the code for the Random Number challenge which has 2 separate conditions, there are variations.
Is there an exception to this that wen there are else if conditions in a conditional there's no requirement for an else keyword?
var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
**if** (parseInt(guess) === randomNumber ) {
correctGuess = true;
} else if ( parseInt(guess) < randomNumber ) {
var guessMore = prompt('Try again. The number I am thinking of is more than ' + guess);
if (parseInt(guessMore) === randomNumber) {
correctGuess = true;
}
} else if ( parseInt(guess) > randomNumber ) {
var guessLess = prompt('Try again. The number I am thinking of is less than ' + guess);
if (parseInt(guessLess) === randomNumber) {
correctGuess = true;
}
}
**if** ( correctGuess ) {
document.write('<p>You guessed the number!</p>');
} **else** {
document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
}
1 Answer
Vittorio Somaschini
33,371 PointsHello Jonathan.
I do NOT think that the else condition is a must. Actually if you got all the cases covered with if and else if statement/s else would be redundant.
If you have cases that are not covered by you statements already, that it will be surely better to add an else statement at least just to print an error or deal with that particular "else" situation..
Talking about the code you provided the second else if could be an else with no problems according to me, but there should be no problem in leaving it like it is in the example.
Vittorio
Jonathan Grieve
Treehouse Moderator 91,254 PointsJonathan Grieve
Treehouse Moderator 91,254 PointsI think I misunderstood Dave in his video,
The requirement is if you use an else it has to go at the end, which makes sense. Question answered. :)