Gabriel Akara
Gabriel Akara

Reputation: 1

Switch statement in JavaScript is not able to run my code Properly

var aged = 14;

switch (aged) {
  case aged <= 13:
    document.write("Child");
    break;
  case aged >= 14 && aged <= 18:
    document.write("Teen");
    break;
  case aged >= 19 && aged <= 59:
    document.write("Adult");
    break;
  default:
    document.write("Boomer");
}

it just keeps outputting BOOMER!! I honestly don't know what to do I got the syntax right but I'm still confused

Upvotes: 0

Views: 51

Answers (1)

user12407908
user12407908

Reputation:

Because each of your case branches provide a boolean value, you need to match against a boolean.

Your logic is such that you want to enter a branch upon a true evaluation, so use true in the head of the switch.

var aged = 14;

switch (true){
    case aged <= 13:
        document.write("Child");
        break;
    case aged >= 14 && aged <= 18:
        document.write( "Teen" );
        break;
    case aged >= 19 && aged <= 59:
        document.write("Adult");
        break;
    default:
        document.write("Boomer");
}


I think if/else would maybe be preferable here.

var aged = 14;

if (aged <= 13) {
        document.write("Child");
} else if (aged >= 14 && aged <= 18) {
        document.write( "Teen" );
} else if (aged >= 19 && aged <= 59) {
        document.write("Adult");
} else {
        document.write("Boomer");
}


You could also use the conditional operator, but I'd use it to provide a value instead of control the flow of the program.

var aged = 14;

var result = aged <= 13               ? "Child" :
             aged >= 14 && aged <= 18 ? "Teen"  :
             aged >= 19 && aged <= 59 ? "Adult" :
                                        "Boomer";
document.write(result);


And your conditions are a little redundant. You can simplify like this:

var aged = 14;

var result = aged <= 13 ? "Child" :
             aged <= 18 ? "Teen"  :
             aged <= 59 ? "Adult" :
                          "Boomer";
document.write(result);

Upvotes: 3

Related Questions