CoffeeScript -Conditions- switch statement - CoffeeScript


A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Here is the syntax of switch in JavaScript.

In JavaScript, after each switch case, we have to use the break statement. If we accidentally forget the break statement, then there is a chance of falling from one switch case to other.

Switch Statement in CoffeeScript

CoffeeScript resolves this problem by using the combination of switch-when-else clauses. Here we have an optional switch expression followed by case statements.

Each case statement have two clauses when and then. The when is followed by condition and then is followed by the set of statements that are to be executed if that particular condition is met. And finally, we have the optional else clause which holds the action for the default condition.

Syntax

Given below is the syntax of the switch statement in CoffeeScript. We specify the expression without parentheses and we separate the case statements by maintaining proper indentations.

Flow Diagram

coffeescript_switch_statement

Example

The following example demonstrates the usage of switch statement in CoffeeScript. Save this code in a file with name switch_example.coffee

Open the command prompt and compile the .coffee file as shown below.

On compiling, it gives you the following JavaScript.

Now, open the command prompt again and run the CoffeeScript file as −

On executing, the CoffeeScript file produces the following output.

Multiple values for when clause

We can also specify multiple values for a single when clause by separating them using commas (,) in the switch cases.

Example

The following example shows how to write a CoffeeScript switch statement by specifying multiple values for the when clause. Save this code in a file with name switch_multiple_example.coffee

Open the command prompt and compile the .coffee file as shown below.

On compiling, it gives you the following JavaScript.

Now, open the command prompt again and run the CoffeeScript file as shown below.

On executing, the CoffeeScript file produces the following output.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

CoffeeScript Topics