Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Switch statement multiple case choises

Stewe Lundin
Mega Guru

If intMonth = 2, 4 or 1 this works just fine but as soon as the value is any other between 3 and 12   exception or 4 the switch statement returns default value of lastday which is 0

Usually this would work and I have used similar code in other switch/case statements elsewhere.

Any suggestions?

Of-course I can use an If/else if statement but this is now a matter of principals.

switch(intMonth){

        case 2:

                  lastday = 28;

                  break;

        case 4|6|9|11:

                  lastday = 30;

                  break;

        case 1|3|5|7|8|10|12:

                  lastday = 31;

}

1 ACCEPTED SOLUTION

Yes, just figured that out as well. This works though:


var intMonth = 6;


var lastday;



switch(intMonth){  


        case 2:  


                  lastday = 28;  


                  break;  


        case 4: case 6: case 9: case 11:  


                  lastday = 30;  


                  break;  


        case 1: case   3: case 5: case 7: case 8: case 10: case 12:  


                  lastday = 31;  


        default:


                  lastday = 1;


}  



gs.print(lastday);



Gives me:



[0:00:00.004] Script completed in scope global: script



*** Script: 30

View solution in original post

5 REPLIES 5

Simon Christens
Kilo Sage

Try the below



case 4:


case 6:


case 9:


case 11:  


lastday = 30;


break;



switch - JavaScript | MDN


sergiu_panaite
ServiceNow Employee
ServiceNow Employee

Stewe,



Shouldn't you use a "||" for a OR condition?


No both || and | gives the same problem.



And I have built similar switch case statements with | and they have worked fine but that is outside of Service Now.


Yes, just figured that out as well. This works though:


var intMonth = 6;


var lastday;



switch(intMonth){  


        case 2:  


                  lastday = 28;  


                  break;  


        case 4: case 6: case 9: case 11:  


                  lastday = 30;  


                  break;  


        case 1: case   3: case 5: case 7: case 8: case 10: case 12:  


                  lastday = 31;  


        default:


                  lastday = 1;


}  



gs.print(lastday);



Gives me:



[0:00:00.004] Script completed in scope global: script



*** Script: 30