Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return value from switch statement?

Tags:

javascript

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?

like image 525
foobar Avatar asked Jul 07 '11 14:07

foobar


2 Answers

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); 
like image 54
helloandre Avatar answered Oct 07 '22 14:10

helloandre


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); 
like image 41
gaby de wilde Avatar answered Oct 07 '22 15:10

gaby de wilde