I have a switch statement with multiple cases in JavaScript. But in one of the cases, I do not want to proceed if a condition is false.
How do I do this.
Take for eg.:
switch (case) {
case "1":
// some code
break;
case "two":
// some code
break;
case "III":
if (!shouldProceed) {
return false;
}
// tasks to be done for case III
break;
case "4":
// case 4 code
break;
default:
// default tasks
break;
}
My task 3 is a switch case, but it is conditional. Is it safe to return false from a case in the above way. What can be a better approach for this?
It is safe if this switch statement is contained inside a function. Just remember that it will also stop the function and return false immediately:
var foo = function (bar) {
switch (bar) {
case 1:
return false;
case 2:
bar++;
break;
default:
return true;
}
return bar;
};
console.log(foo(1)); // false
console.log(foo(2)); // 3
console.log(foo(3)); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With