If you want something returned, stick it in a function then use the switch return statement in JavaScript. You don’t need the clutter of break;
statements if you wrap it in a function.
function switchResult(a){
switch(a){
default:
return "OK";
}
}
var a = switchResult(3);
Example switch case with return statement in JavaScript
Simple example code return statements inside the cases specify what the function will return given different conditions.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function switchResult(a){
switch(a){
case 1: return "FOO";
case 2: return "BAR";
case 3: return "FOOBAR";
default:
return "OK";
}
}
var res = switchResult(3);
console.log(res)
</script>
</body>
</html>
Output:
ES6 lets you do this using an immediately-invoked lambda:
const a = (() => {
switch(3) {
default: return "OK";
}
})();
Is returning out of a switch statement considered better practice than using a break?
Answer: A break will allow you to continue processing the function. Just returning out of the switch is fine if that’s all you want to do in the function.
switch using return:
function myFunction(opt)
{
switch (opt)
{
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
default: return "";
}
}
switch using break:
function myFunction(opt)
{
var retVal = "";
switch (opt)
{
case 1:
retVal = "One";
break;
case 2:
retVal = "Two";
break;
case 3:
retVal = "Three";
break;
}
return retVal;
}
Do comment if you have any doubts or suggestions on this JS switch case.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version