Conditional Statements in TypeScript – if…else

Conditional Statements are used to make decisions in the code and execute a set of statements accordingly. If a condition is true, one set of statements is executed. If the condition is false, no or another set of statements is executed.

There are two types of conditional statements: if and switch. In this article, we will be discussing various forms of if-statements.

if statement

Only if statement is included with a condition. If the result of this condition is true, a set of statements is executed. No else condition is present.
Below is an example when if condition returns false.

var num1:number = 100;
if(num1>200){
console.log("Inside if statement");
}
console.log("Outside if statement");

Below is the output of above code:

Below is an example when if condition returns true.

var num1:number = 100;
if(num1<200){
console.log("Inside if statement");
}
console.log("Outside if statement");

Below is the output of above code:

if…else statement

Here, when the condition is true, if block is executed. When the condition is false, else block is executed.
Below is the example when condition is true and if block is executed.

var num1:number = 100;
if(num1<200){
    console.log("Inside if, as condition is true");
}
else{   
    console.log("Inside else, as condition is false");
}

Below is the output of above code:

Below is the example when condition is false and else block is executed.

var num1:number = 100;
if(num1>200){
    console.log("Inside if, as condition is true");
}
else{   
    console.log("Inside else, as condition is false");
}

Below is the output of above code:

if…else if..else Statement

Below are some sample codes:

var num1:number = 100;
var num2:number = 200;
if(num1>num2){
    console.log(num1 + " is greater than " + num2);
}
else if(num1<num2){   
    console.log(num1 + " is less than " + num2);
}
else{
    console.log(num1 + " is equal to " + num2);
}

Below is the output of above code:

Another Example:

var num1:number = 100;
var num2:number = 100;
if(num1>num2){
    console.log(num1 + " is greater than " + num2);
}
else if(num1<num2){   
    console.log(num1 + " is less than " + num2);
}
else{
    console.log(num1 + " is equal to " + num2);
}

Below is the output of above code:

Nested If

We can nest if statements inside another if or else block. Below is an example related to this:

var num1:number = 100;
var num2:number = 200;
var num3:number = 100;
if(num1>num2){
    console.log(num1 + " is greater than " + num2);
}
else if(num1<num2){   
    console.log(num1 + " is less than " + num2);
    if(num1 == num3){
        console.log(num1 + " is equal to " + num3);
    }
    else{
        console.log(num1 + " is not equal to " + num3);
    }
}
else{
    console.log(num1 + " is equal to " + num2);
}

Below is the output of above code:

Design a site like this with WordPress.com
Get started