TypeScript if else – Conditional Statement
TypeScript if else is an extension to if conditional statement. else block is an optional block that can follow if block. if else block facilitates the branching of execution flow into one of the two blocks based on a condition.
If the return value of expression following if keyword is true, then the code block right after if statement is executed, otherwise the code block after else block is executed.
Syntax
Following is the syntax of TypeScript if-else statement :
if(expression) {
/* if block statements */
} else {
/* else block statements */
}
- expression should return a boolean value.
Example 1 – TypeScript If Else
Following is an example TypeScript code to demonstrate if conditional statement.
example.ts
var a:number = 1
var b:number = 3
if(a == 1){
console.log("value of a is 1.")
} else {
console.log("value of a is not 1.")
}
if(a == b){
console.log("a and b are equal.")
} else {
console.log("a and b are not equal.")
}
When the above code is compiled using typescript compiler, tsc example.ts
, following JavaScript code is generated.
example.js
var a = 1;
var b = 3;
if (a == 1) {
console.log("value of a is 1.");
}
else {
console.log("value of a is not 1.");
}
if (a == b) {
console.log("a and b are equal.");
}
else {
console.log("a and b are not equal.");
}
For this example, you might notice that there is no difference between TypeScript and JavaScript if-else code blocks.
TypeScript If Else If
Instead of a code block following else keyword, another if statement could be placed forming an if-else-if ladder statement.
example.ts
var a:number = 1
var b:number = 3
if(a == b){
console.log("a and b are equal.")
} else if (a>b) {
console.log("a is greater than b.")
} else if (a<b) {
console.log("a is less than b.")
}
You can find out how this nested if-else would translate to JavaScript, an an exercise.
Conclusion
In this TypeScript Tutorial, we have learnt about if-else conditional statement in TypeScript, its syntax and also working examples.