el_tinha
el_tinha

Reputation: 11

How to configure switch case statements with 2 boolean variables?

I am new to JavaScript and trying to implement switch case statements to output one of 4 options according to the combination of values of 2 Boolean variables. However, it seems that javascript is ignoring the second variable (adultCheck). Can you tell me what I am doing wrong please?

Thank you!

let raceNumber = Math.floor(Math.random() * 1000);
let earlyRegistry = false;
let adultCheck = true;
let runnerAge = 19;

//determines if runner is an adult or not
runnerAge > 18 ? adultCheck = true : adultCheck = false;
//assigns racenumber according to runner having registered early or not
earlyRegistry ? raceNumber += 1000 : raceNumber;

//below logs for checks only
console.log(earlyRegistry);
console.log(raceNumber);
console.log(runnerAge);
console.log(adultCheck);

//determines race start time according to runner being adult or not and if registered early or not
switch (earlyRegistry && adultCheck) {
  case (true && true):
    console.log(`Your race number ${raceNumber} will start at 09:30am`);
    break;
  case (false && true):
    console.log(`Your race number ${raceNumber} will start at 11am`);
    break;
  case (true && false):
    console.log(`Your race number ${raceNumber} will start at 12:30pm`);
    break;
  case (false && false):
    console.log(`Your race number ${raceNumber} will start at 12:30pm`);
    break;
  default:
    console.log('Invalid item');
    break;
}

Upvotes: 0

Views: 122

Answers (2)

Mr. Hedgehog
Mr. Hedgehog

Reputation: 2885

As for your particular piece of code, @mplungjan gave very good answer. I'll just describe how you can do it your way, which would be nice in complex scenarios, but overhead in simpler cases.

In general, you can name your states and use switch on said names. How exactly you will do your naming is not particularly relevant. For example you can do it like this:

let state;
if (earlyRegistry && adultCheck) state = 'early_adult';
if (!earlyRegistry && adultCheck) state = 'late_adult';
if (earlyRegistry && !adultCheck) state = 'early_child';
if (!earlyRegistry && !adultCheck) state = 'late_child';

Then you use switch. This is pretty readable and usable, but it's not practical, so you can just replace setting value to state variable to actually doing what you want to do with them.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178285

It is not recommended to abuse a switch side effect.

Your code can be written in a simpler fashion

I use ONE ternary but could use a nested one, but this is more readable

let time = "12:30pm";
if (adultCheck) time = earlyRegistry ? "09:30am" : "11am";
console.log(`Your race number ${raceNumber} will start at ${time}`);
     

Upvotes: 1

Related Questions