Switch in Fortress
Here’s a translation of the provided example into the JavaScript programming language:
Switch statements provide an efficient way to handle multiple conditional branches.
A Basic Switch
Here’s a basic switch
.
const i = 2;
console.log('Write', i, 'as');
switch (i) {
case 1:
console.log('one');
break;
case 2:
console.log('two');
break;
case 3:
console.log('three');
break;
}
Multiple Expressions in Case Statements
You can use commas to separate multiple expressions in the same case
statement. The default
case is also optional and can be used when none of the cases match.
const day = new Date().getDay();
switch (day) {
case 0: // Sunday
case 6: // Saturday
console.log("It's the weekend");
break;
default:
console.log("It's a weekday");
break;
}
Switch Without an Expression
Switch without an expression is an alternative way to express if/else logic. case
expressions can be non-constants.
const t = new Date().getHours();
switch (true) {
case t < 12:
console.log("It's before noon");
break;
default:
console.log("It's after noon");
break;
}
Type Switch
JavaScript doesn’t have built-in type switching like some other languages but we can mimic it using typeof
or other methods.
const whatAmI = function(i) {
switch (typeof i) {
case 'boolean':
console.log("I'm a bool");
break;
case 'number':
console.log("I'm an int");
break;
default:
console.log(`Don't know type ${typeof i}`);
break;
}
};
whatAmI(true);
whatAmI(1);
whatAmI("hey");
Running the Code
In Node.js, you can execute these scripts directly:
$ node switch_example.js
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string
Now that we understand JavaScript’s switch
statements, let’s explore more about the language’s features.