Title here
Summary here
Branching with if
and else
in TypeScript is straightforward.
// Here's a basic example.
if (7 % 2 === 0) {
console.log("7 is even");
} else {
console.log("7 is odd");
}
// You can have an `if` statement without an else.
if (8 % 4 === 0) {
console.log("8 is divisible by 4");
}
// Logical operators like `&&` and `||` are often
// useful in conditions.
if (8 % 2 === 0 || 7 % 2 === 0) {
console.log("either 8 or 7 are even");
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
let num = 9;
if (num < 0) {
console.log(num, "is negative");
} else if (num < 10) {
console.log(num, "has 1 digit");
} else {
console.log(num, "has multiple digits");
}
To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:
$ tsc if-else.ts
$ node if-else.js
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that you do need parentheses around conditions in TypeScript, and the braces are required for multi-line blocks but optional for single-line statements.
TypeScript (and JavaScript) do have a ternary operator (?:
), which can be used for simple conditional expressions:
let result = condition ? valueIfTrue : valueIfFalse;
This can be useful for assigning values based on a condition, but for more complex logic, full if
/else
statements are often clearer.