Switch case statement in a script

jasleen3
Kilo Contributor

Hi,

My script is running fine if I am using "if statement", but if i use switch it's not working at all.

find_real_file.png

19 REPLIES 19

Logs are fine..Made the changes but no luck



find_real_file.png


You really only need to use toString() either when assigning the the country variable on line 8, or in the switch itself (line 15).



Have you checked the system logs?




System Logs> Warnings


System Logs> Errors



for any signs of trouble?


I'm having a similar problem in my Helsinki instances.



I have a scripted web service which calls some code in a script include that effectively looks like this.


function foo(bar) {


        switch(bar) {


                  case "a":


                            return "alpha";


                  case "b":


                            return "bravo";


                  case "c":


                            return "charlie";


                  default:


                            return "unknown";


        }


}



foo("b"); // should return "bravo" but instead returns "unknown"



But the problem I'm having is that no matter what value I pass into this thing, the default case always fires. If I switch it to if/else, it works.



function foo(bar) {


        if (bar == "a") {


                  return "alpha";


        }


        else if (bar == "b") {


                  return "bravo";


        }


        else if (bar == "c") {


                  return "charlie";


        }


        else {


                  return "unknown";


        }


}


foo("b"); // returns "bravo"



I have noticed similar behavior in other places and have had to convert switches to if/else piles several times. What's going on here?


Hey John,



I ran your script of switch case and it works fine on my helsinki instance.



Darshak


Thanks for the response. That's actually exactly my point. If you take that code and run it as a background script, or in the JS Executor modal, it runs fine. But when it's actually in the script include being called from the scripted web service, it skips to the default case. In fact, I've even tested it like this:



switch(bar) {


        case "alpha":


                  return "a";


        /* snip */


        default:


                  return "unknown '" + bar + "'";


}



Every time, it return "unknown 'alpha'" and you can clearly see the bar value matches exactly one of the cases. I've also tried:



switch(bar.toString()) { // <-- added .toString()


        case "alpha":


                  return "a";


        /* snip */


        default:


                  return "unknown '" + bar + "'";


}



Same result there too.