Profile image of Bobby7
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

Permalink

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

Profile image of hrsetyono
Submitted by hrsetyono
over 11 years

1 comments

Profile image of Bobby7
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.