How to get return value from switch statement?

Javascript

Javascript Problem Overview


In chrome's console, when I type:

> switch(3){default:"OK"}
  "OK"

So looks like the switch statement has a return value. But when I do:

> var a = switch(3){default:"OK"}

It throws a syntax error "Unexpected Token switch"

Is it possible to capture the return statement of the switch?

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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);

Solution 3 - Javascript

ES6 lets you do this using an immediately-invoked lambda:

const a = (() => {
  switch(3) {
    default: return "OK";
  }
})();

Solution 4 - Javascript

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.

Solution 5 - Javascript

I recently had to test if switch statements can return values. I was pretty sure they could and implemented a quick terse function to test it in the FF and Chrome console.

function switchController(setFlag) {
  switch (setFlag) {
    case true:   return setFlag;
    case false:  return setFlag;
  }
}

console.log(switchController(true));
console.log(switchController(false));

You should get output in the console of:

true
false

You can view return values using console.log()

Solution 6 - Javascript

Chrome is just showing you the last value evaluated. There is no output from a switch. Just use a variable.

var a; 

switch(3)
{
  default:
    a = "OK";
}

Solution 7 - Javascript

What you are seeing in the chrome dev tools is the completion value of the switch statement. Basically the value of the last evaluated expression (but not quite, e.g. the completion value of var a = 42 is not 42). The completion value is a construct in ECAMScript that is usually hidden from the programmer. Though, it also comes up as the return value of eval().

The grammar for variable assignments expects an expression on its right-hand side so using a switch statement is that place is a syntax error:

"var" <name> "=" <expression> 

Basically the difference between statements and expressions is that expressions compute a value while statements do not. Function calls, arithmetic, and literals are all expressions for example. "If" and "switch" statements are not.

There is no way to capture the completion value of any statement expects perhaps wrapping it in an eval call:

var a = eval('switch (3) { default: "OK" }')
console.log(a) // => "OK"

But using eval for this would not be a good idea.

Unfortunately, there is no great way to archive what you want to do. Like other answers mentioned, you could wrap the switch in a function (or IIFE) and use return statements to get the value out:

const a = (() => {
  switch(3) { default: return "OK"; }
})();

You might find this not to be an ideal solution and you are not the only one having this issue with JavaScript.

It is my understanding that this is one of the motivations of the pattern-matching ECAMScript proposal. But the proposal is in Stage 1 and not yet ready for production use.

Furthermore, you might want to write your code in a way that does not need switch statements at all. A while ago I came across the following pattern that is apparently common in Lua but I never saw it used in JavaScript:

Instead of using a switch statement you could put all your cases as properties in a JavaScript object and use functions as values instead of the logic in the individual case blocks. This might look something like this:

const cases = {
  "FOO": () => 1,
  "BAR": () => 2,
  "BAR": () => 3,
};


const value = "FOO";
const result = cases[value]();
console.log(result); // => 1

Instead of this:

let result;
switch (value) {
	case "FOO":
		result = 1;
		break;
	case "BAR":
		result = 2;
		break;
	case "BAR":
		result = 3;
		break;
}

If you need non-string cases you might want to use a Map.

Solution 8 - Javascript

You can use an object

const a = { [enum.3]: "OK" }[3] ?? "default"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfoobarView Question on Stackoverflow
Solution 1 - JavascripthelloandreView Answer on Stackoverflow
Solution 2 - Javascriptgaby de wildeView Answer on Stackoverflow
Solution 3 - JavascriptzarvaxView Answer on Stackoverflow
Solution 4 - JavascriptGuffaView Answer on Stackoverflow
Solution 5 - JavascriptNickersFView Answer on Stackoverflow
Solution 6 - JavascriptDaniel A. WhiteView Answer on Stackoverflow
Solution 7 - JavascriptMoritzView Answer on Stackoverflow
Solution 8 - JavascriptCervEdView Answer on Stackoverflow