Switch Statement

0 Robert Summers · October 15, 2014
I have made this switch statement but if anyone is over 21, how do i output your over 21.


var age = 21;

switch(age){
case 16: 
document.write("Your only 16 years old!!");
break;
case 17: 
document.write("Your underage.");
break;
case 18: 
document.write("You may enter");
break;
default:
document.write("Your not 18");
break;

}

Many thanks for your help.

Post a Reply

Replies

Oldest  Newest  Rating
+1 Phillip Drake · October 17, 2014
Hello, I hope this is the answer to your question.  There are several solutions to the question you are asking.  Your code and output would depend on what you are trying to accomplish.  Here are some suggestions:


var age = 21;

switch(age){
case 16: 
document.write("Your only 16 years old!!");
break;
case 17: 
document.write("Your underage.");
break;
case 18: 
document.write("You may enter");
break;
case 21:
document.write("You're over 21!");
break;
default:
document.write("Your not 18");
break;

}

Better and more accurate suggestion:  


var age = 21;

switch(age){
case 16: 
document.write("Your only 16 years old!!");
break;
case 17: 
document.write("Your underage.");
break;
case 18: 
document.write("You may enter");
break;
default:
if ( age < 21 ) {
document.write("You're not 18!");
} else if ( age >= 21 ) {
document.write("You're over 21!");
}
break;

}
+1 Robert Summers · October 19, 2014
Thank you Philip your answer has worked :)
+1 Phillip Drake · October 20, 2014
You're welcome!  Anytime!
  • 1

Javascript

107,297 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators