Drakon.Tech logo
Get started
Drakon.Tech documentationProgramming in DRAKONThe basics of programming with Drakon.TechHello worldVariables and functionsif-else | Question iconswitch-case | the Choice iconThe foreach loopThe arrow (while) loopSilhouetteClassesLambdas and exceptionsAdvanced programming methodsGame examplesThe source codeLegacy tutorials (JavaScript 0.2)

switch-case | the Choice icon

Ru | En

Source code: Choice

The Choice icon compares an expression to several values. For such a case, we could use a sequence of Question icons, but Choice is a more concise option. The Choice icon is the equivalent of the switch-case statement in JavaScript.

Let's take the printNumber function from the article on the Question icon. Here, we compare the number variable to values 10 and 20.

A more complex decision tree with the Question icon

Let's rewrite this function with a Choice icon.

The Choice icon

Note that the expression in the Choice icon will be evaluated only once.

We put each of the values in a separate Case icon. We can add more case icons if we want. The empty Case icon to the right means "all other values."

Let's build the module and run the app.

10 "ten"
20 "twenty"
30 "some other value"

If we delete the empty Case icon, Drakon.Tech will add a throw statement for all other values besides 10 and 20.

The Choice icon

Let's test it. Right! We get an error: "unexpected choice value."

10 'ten'
20 'twenty'
Uncaught Error: Unexpected case value: 30
    at printNumber (choice.js:30:31)
    at Object.main (choice.js:9:9)
    at choice_app.js:3:14
    at choice_app.js:4:3

Case icons can contain any expressions, not only constants. Let's put a variable in a Case icon instead of a constant.

The Choice icon with a variable in a Case

See, we get the same result as before.

10 "ten"
20 "twenty"
30 "some other value"
Source code: Choice
Drakon.Tech logo
Drakon.Tech home
Programming in DRAKONThe basics of programming with Drakon.TechAdvanced programming methodsThe source codeLegacy tutorials (JavaScript 0.2)