Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement to compare values greater or less than a number

I want to use the switch statement in some simple code i'm writing.

I'm trying to compare the variable in the parenthesis with values either < 13 or >= 13.

Is this possible using Switch?

var age = prompt("Enter you age");
switch (age) {
    case <13:
        alert("You must be 13 or older to play");
        break;
    case >=13:
        alert("You are old enough to play");
        break;
}
like image 498
CP Creative Studio Avatar asked Sep 15 '15 02:09

CP Creative Studio


3 Answers

Directly it's not possible but indirectly you can do this

Try like this

switch (true) {
    case (age < 13):
        alert("You must be 13 or older to play");
        break;
    case (age >= 13):
        alert("You are old enough to play");
        break;
}

Here switch will always try to find true value. the case which will return first true it'll switch to that.

Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.

like image 99
Anik Islam Abhi Avatar answered Oct 24 '22 05:10

Anik Islam Abhi


Instead of switch you can easily to the same thing if else right?

if(age<13)
    alert("You must be 13 or older to play");
else
    alert("You are old enough to play");
like image 20
Manikanta Reddy Avatar answered Oct 24 '22 07:10

Manikanta Reddy


This worked in my case:

var enteredAge = prompt("Enter your age");
let ageMoreThan13 = parseInt(enteredAge) >= 13;
let ageLessThan13 = parseInt(enteredAge) < 13;
switch (ageMoreThan13 || ageLessThan13) {
    case ageLessThan13:
        alert("You must be 13 or older to play");
        break;
     case ageMoreThan13:
        alert("You are old enough to play");
        break;
}
like image 21
Alaska_yung Avatar answered Oct 24 '22 07:10

Alaska_yung