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?
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?
Share Improve this question asked Feb 14, 2014 at 10:11 KingJulianKingJulian 9731 gold badge9 silver badges20 bronze badges 3-
Yes you can
return false
, it's safe. – Denys Séguret Commented Feb 14, 2014 at 10:12 - there's no problems with doing that – Tanner Commented Feb 14, 2014 at 10:12
- As long as you don't have any code you still need to execute after the switch statement that should be fine. – Anthony Grist Commented Feb 14, 2014 at 10:13
1 Answer
Reset to default 4It 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