Submitted by Bobby7
over 11 years
Can you use else if / if else statements multiple times?
I know the following doesn’t work:
var computerChoice = Math.random();
if (computerChoice<=0.25){
computerChoice = "rock";
}
else if (computerChoice<=0.50){
computerChoice = "paper";
else if (computerChoice<=0.75){
computerChoice = "Tank";
}
else {
computerChoice = "scissors";
}
But out of curiosity, if you wanted more choices using Math.random
, are you limited to just if
, else if
, and else
? If you are, do you get round this by nesting if/else statements inside other ones or is there another method?
Answer 514a8bea4a9e0e2522000cf1
0 votes
You can use multiple else if
but each of them must have opening and closing curly braces {}
.
if (){
}
else if (){
}
else if(){
}
else{
}
You can replace if
with switch
statement which is simpler but only for comparing same variable.
You will learn switch
in Section 5 - Control Flow. Part 2
Submitted by hrsetyono
over 11 years
1 comments
Submitted by Bobby7
over 11 years
Yeah, I figured that out as I completed more exercises. At the time, I didn’t realise I’d missed the closing brace after ‘paper’, which confused me. Thanks for replying.
Popular free courses
- Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly4 Lessons - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly11 Lessons - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly6 Lessons