Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return false from a switch statement

Tags:

javascript

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?

like image 613
KingJulian Avatar asked Nov 29 '25 20:11

KingJulian


1 Answers

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
like image 160
Danilo Valente Avatar answered Dec 02 '25 10:12

Danilo Valente



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!