This forum is now read-only. Please use our new forums! Go to forums

Close banner
0 points
Submitted by Bobby7
about 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(){

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 Henner Setyono
about 11 years


Bobby7 about 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.