Switch case statement in a script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2017 05:42 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2017 06:01 AM

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2017 06:08 AM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-09-2017 01:19 PM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-09-2017 01:40 PM
Hey John,
I ran your script of switch case and it works fine on my helsinki instance.
Darshak
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎08-09-2017 01:47 PM
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.