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
0 Robert Summers · October 15, 2014
Thanks mate, it has worked. :)
0 Ibrahim Tuzlak · October 15, 2014
As far as I know, you may need to change it to something like this:


var age = 21;

switch(true){
case (age == 16):
document.write("You are only 16 years old!!");
break;
case (age == 17):
document.write("You are underage.");
break;
case (age == 18): 
  document.write("You may enter");
  break;
  case (age > 20):
document.write("You are over 21");
break;
default:
document.write("You are not 18");
break;
}

OR use if/else if.

EDIT: switch(age) is the right way, it's just you can't use bigger than (>), less than (<) etc. in your example, so it needed to be changed.
  • 1

Javascript

127,967 followers
About

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

Links
Moderators