O'Reilly logo

CoffeeScript Programming with jQuery, Rails, and Node.js by Michael Erasmus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Switch statements

In CoffeeScript, switch statements take a different form, and look a lot less like JavaScript's Java-inspired syntax, and a lot more like Ruby's case statement. You don't need to call break to avoid falling through to the next case condition.

They have the following form:

switch condition 
  when … then …
   ….
else …

Here, else is the default case.

Like everything else in CoffeeScript, they are expressions, and this can be assigned to a value.

Let's look at an example:

CoffeeScript:

languages = switch country
  when 'france' then 'french'
  when 'england', 'usa' then 'english'
  when 'belgium' then ['french', 'dutch']
  else 'swahili'

JavaScript:

var languages; languages = (function() { switch (country) { case 'france': return 'french'; case 'england': ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required