Tutorial 4. Choice
The Choice icon compares an expression to several values. We could use a sequence of Question icons, but Choice is a more concise option for this case. The Choice icon is the equivalent of the switch statement in JavaScript.
Let's take the printNumber function from the previous tutorial. Here, we compare the number variable to values 10 and 20.
Let's rewrite this function with a 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 icon to the right means "all other values."
Let's build and run the project.
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.
Let's test it. Right! We get an error: "unexpected choice value."
10 "ten" 20 "twenty" tutorial_04_choice.js:18 Uncaught Error: Unexpected Choice value: 30 at printNumber (tutorial_04_choice.js:18) at main (tutorial_04_choice.js:7) at tutorial_04_choice.js:24 at tutorial_04_choice.js:26
Case icons can contain any expressions, not only constants. Let's put a variable in it instead of a constant.
See, we get the same result as before.
10 "ten" 20 "twenty" 30 "some other value"