CoffeeScript: switch conditional statement


Switch statement in CoffeeScript.

switch

switch” will be written like the following.

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.

Attention

Be careful not to do like the following code.

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