switch-statementcoffeescript

Coffeescript: unexpected then in a switch statement


I'm trying to use a simple switch statement but it doesn't compile. Here's the code:

tag = 0 
switch tag
    when 0 then
        alert "0"
    when 1 then 
        alert "1"

The coffeescript compiler complains about an "unexpected then" in the line after the switch statement. I changed the code to this:

switch tag
    when 0 then alert "0"
    when 1 then alert "1"

and it works fine.

But I need multiple statements on multiple lines in the then parts of the switch statement. Is that impossible ?


Solution

  • Just drop the then altogether. You only need it when you don't want to have a new indented block.

    tag = 0 
    switch tag
        when 0
            alert "0"
        when 1
            alert "1"
    

    (if works that way, too)