How to get return value from switch statement?
That's because when you're putting that into the Chrome console, you're short-circuiting it. It's just printing 'OK' because it's reaching the default case, not actually returning something.
If you want something returned, stick it in a function, and return the 'OK' from in the default case.
function switchResult(a){
switch(a){
default:
return "OK";
}
}
var a = switchResult(3);
ES6 lets you do this using an immediately-invoked lambda:
const a = (() => {
switch(3) {
default: return "OK";
}
})();
Perhaps interesting to note that you dont need the clutter of ;break;
statements if you wrap it in a function. (as described by heloandre)
function switchResult(a){
switch(a){
case 1: return "FOO";
case 2: return "BAR";
case 3: return "FOOBAR";
default: return "OK";
}
}
var a = switchResult(3);
No, the switch
doesn't have a return value. What you see in the console is the return value of the statement inside the switch
containing only a string literal value.
A statement can have a return value. An assignment for example has the assigned value as return value, and post-incrementing a value returns the result after incrementing:
> a = 42;
42
> a++;
43
A statement containing just a value will have that value as return value:
> 42;
42
> "OK";
"OK"
A statement like that is however only useful in the console, for example for showing the value of a variable. In code it won't accomplish anything.