switch-case | the Choice icon
Ru | En
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.
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 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.
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.
See, we get the same result as before.
10 "ten" 20 "twenty" 30 "some other value"