1

I have a problem with the 'case' statement in the 'switch' statement in java script. My question is how to write more than one number in the 'case' statement and save all the work on writing multiple of commands for each number , ill try to explain myself better. i want to write in the case statement the number 10-14 (10,11,12,13,14). how can i write it? thanks for helping and sorry for my bad english.

name = prompt("What's your name?")  
switch (name)  
{  
    case "Ori":  
        document.write("<h1>" + "Hello there Ori" + "<br>")  
        break;  

    case "Daniel":  
        document.write("<h1>" + "Hi, Daniel." + "<br>")  
        break;  

    case "Noa":  
        document.write("<h1>" + "Noa!" + "<br>")  
        break;  

    case "Tal":  
        document.write("<h1>" + "Hey, Tal!" + "<br>")  
        break;  

    default:  
        document.write("<h1>" + name + "<br>")  
}  
age = prompt ("What's your age?")
switch (age)
{
case  "10":
document.write("you are too little" + name)
break;

case "14":
document.write("So , you are in junior high school" + name)
break;

case  "18":
document.write("You are a grown man" + name)
break;

default:
document.write("That's cool" + name)
break;
}
Sagiv Zafrani
  • 13
  • 1
  • 3

5 Answers5

2

Check out this answer Switch on ranges of integers in JavaScript

In summary you can do this

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x > 4 && x < 9):
        alert("between 5 and 8");
        break;
    case (x > 8 && x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

but that sort of defeats the purpose of a switch statement, because you could just chain if-else statments. Or you can do this:

switch(this.dealer) {
        case 1:
        case 2:
        case 3:
        case 4:
            // Do something.
            break;
        case 5:
        case 6:
        case 7:
        case 8:
            // Do something.
            break;
        default:
            break;
    }
Community
  • 1
  • 1
fxfilmxf
  • 582
  • 6
  • 13
0

use this, if you dont provide break then control will fall down, In this way you can match for group of numbers in switch.

case 10:
case 11:
case 12:
case 14:
case 15: document.write("i am less than or equal to 15");break;
Voonic
  • 4,667
  • 3
  • 27
  • 58
0

Say you wanted to switch on a number 10-14 (10,11,12,13,14) you can chain the cases together:

switch(number) {
  case 10: 
  case 11: 
  case 12:
  case 13:
  case 14:
    alert("I'm between 10 and 14");
    break;
  default:
    alert("I'm not between 10 and 14");
    break;
}
Wil
  • 4,887
  • 3
  • 22
  • 30
0

You can simply omit the break; statement.

switch (2) {
    case 1: case 2: case 3:
        console.log('1 or 2 or 3');
        break;
    default:
        console.log('others');
        break;
}

I wanted to play with the concept a bit, I do not recommend this approach, however you could also rely on a function that will create a control flow function for you. This simply allows some syntaxic sugar.

var createCaseFlow = (function () {
    var rangeRx = /^(\d)-(\d)$/;

    function buildCases(item) {
        var match = item.match(rangeRx),
            n1, n2, cases;

        if (match) {
            n1 = parseInt(match[1], 10);
            n2 = parseInt(match[2], 10);
            cases = [];

            for (; n1 <= n2; n1++) {
                cases.push("case '" + n1 + "':");
            }

            return cases.join('');
        }

        return "case '" + item + "':";
    }

    return function (cases, defaultFn) {
        var fnStrings = ['switch (value.toString()) { '],
            k;

        for (k in cases) {
            if (cases.hasOwnProperty(k)) {
                fnStrings.push(k.split(',').map(buildCases).join('') + "return this[0]['" + k + "'](); break;");
            }
        }

        defaultFn && fnStrings.push('default: return this[1](); break;');

        return new Function('value', fnStrings.join('') + '}').bind(arguments);
    };

})();

var executeFlow = createCaseFlow({
        '2-9': function () {
            return '2 to 9';
        },
        '10,21,24': function () {
            return '10,21,24';
        }
    },
    function () {
        return 'default case';
    }
);

console.log(executeFlow(5)); //2 to 9
console.log(executeFlow(10)); //10,21,24
console.log(executeFlow(13)); //default case
plalx
  • 42,889
  • 6
  • 74
  • 90
-1

You have already gotten a few answers on how to make this work. However, I want to point out a few more things. First off, personally, I wouldn't use a switch/case statement for this as there are so many similar cases – a classic if/elseif/else chain feels more appropriate here.

Depending on the use-case you could also extract a function and then use your switch/case (with more meaningful names and values, of course):

function getCategory (number) {
    if(number > 20) {
        return 3;
    }
    if(number > 15) {
        return 2;
    }
    if(number > 8) {
        return 1;
    }

    return 0;
} 

switch( getCategory( someNumber ) ) {
    case 0:
        // someNumber is less than or equal to 8
        break;
    case 1:
        // someNumber is any of 9, 10, 11, 12, 13, 14, 15
        break;
    // ...
}

If the intervals are equally spaced, you could also do something like this:

switch( Math.floor( someNumber / 5 ) ) {
    case 0:
        // someNumber is any one of 0, 1, 2, 3, 4
        break;
    case 1:
        // someNumber is any one of 5, 6, 7, 8, 9
        break;
    // ...
}

Also, it should be noted that some people consider switch/case statements with fall-throughs (= leaving out the break; statement for come cases) bad practice, though others feel it's perfectly fine.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
  • I'm always for playing around, but I wouldn't use that in production code, ever. It's a nice fiddle, though. – Ingo Bürk Sep 19 '13 at 18:24
  • Well, it could be harmful on performance but other than this I am not sure it isin't a viable solution, especially with good test coverage. – plalx Sep 19 '13 at 18:30
  • I don't really like the idea of using string values for number comparison, I'd like to stick with the same type. It certainly breaks any IDE's functionality for recognizing what's going on. I just don't see the benefit over if/elseif/else or, if the use-case allows for it, the category kind of handling, that makes me go "Yes, that's it!" – Ingo Bürk Sep 19 '13 at 19:13
  • Unless `switch` was dramatically faster than `if else if`, which isin't the case (at least in all browsers), I agree that there isin't any advantage, perhaps just slightly more readable. – plalx Sep 19 '13 at 21:06