Switch statement in CoffeeScript.
switch
“switch” will be written like the following.
|
1 2 3 4 5 6 7 8 9 |
switch v when 1 then abc when 2 method 1 method 2 when 3, 4 method 3 else method 4 |
In javascript, “switch” needs a round bracket, but CoffeeScript doesn’t.
In C or javascript, we should divide cases with “case“, but in coffeescript we should do with when like ruby. If the statement after “when” is written in one line, “then” is needed. If you write procedure with LF, “then” is not needed and error occurs when you write then in that case.
After “when“, you can write multi values.
As for “switch” in javascript, we should write “break” after “when” and control following procedure, but we don’t need “break” in CoffeeScript. In another words, fall-through is disabled.
If any value written after “when” doesn’t match to the value, the process goes to “else“. “then” is not needed after “else“, even if post-statement is written in one line.
And you can write conditional statement after “when“. “switch” itself returns value, so you can write like substitution.
|
1 2 3 4 |
r = switch when v < 1 then 'A' when v < 2 then 'B' else 'C' |
Attention
Be careful not to do like the following code.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
c = 1 v = switch when c > 0 then 'A' else 'B' # => v = 'A' v = switch true when c > 0 then 'A' else 'B' # => v = 'A' v = switch false when c > 0 then 'A' else 'B' # => v = 'B' v = switch 1 when c > 0 then 'A' else 'B' # => v = 'B' |
Be careful not to write the statement which should be evaluated as boolean (true/false) after “when“. (Look into how it to be converted to javascript for detail.)


