Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switch/case using logic operators such as >= and &&

I have this code that first reads which position of a checkbox is checked and then executes several ifs. Then I thought I could make the code smaller if I used switch/case, while also portfolio-ing the command for later uses. The command was like this:

if (fsex[0].checked {
gender = 'man'
if (age >= 0 && age <= 10) {
img.setAttribute('src', 'male-baby.png')
} else if

I tried using switch by changing what is bellow "gender" line to something like this:

switch (age) {
case (age >=0 && age <= 10):
img.setAttribute('src', 'male-baby.png')
break
case ...etc

This didn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Then I tried with case >=0, which then the VSCode immediatly returns a sintax error "expression expected.

Is there a way I can use switch/case to this one? Or I should just stick with several if/ else ifs?

>Solution :

You can use this "trick":

const age = 14;

switch(true) 
{
  case age > 5 && age <= 10:
    console.log('bla 1');
  break;
  case age > 10 && age <= 20:
    console.log('bla 2');
  break;
  case age > 20 && age <= 30:
    console.log('bla 3');
  break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading