Decision Making or if and switch condition

Like all other programming languages in TypeScript also there is a conditional decision-making system and they are mainly

  1. if case and
  2. switch case

The if Case in TypeSaript:

if a condition is satisfied then only it lets execute the code which is inside of the if case else executes from the code after the if block.

Example:

 var num:number = 5;
if(num > 0){
console.log('The number is positive and value is : ' + num);
}

If Else Block:

Sometime there may else condition that is if the condition satisfied the go to the if block else goes to the else block.

Example:

 var num2:number = 10;
if(num2%2 == 0){
console.log('The number ' + num2 + ' is even');
}else{
console.log('The number ' + num2 + 'is odd');
}

Nested if-else:

The nested if-else is if a condition is satisfied then it lets enter the block of the condition satisfied if block, and inside the block, there is another conditional if block and inside that and so on.

Example:

 var num3:number = 20;
if(num3%2==0){
console.log('The number is even');
if(num%5 ==0){
console.log('The number can be divided by 5');
if(num3%50==0){
console.log('The number can divided by 50');
}else{
console.log('The number is not dividable by 50');
}
}
}else{
console.log('The number is odd');
}

the switch is used for multiple time used if condition ie suppose color if the color is red show some picture else if the color is blue show another else if the color is green show some other and so on

The example is given below.

The switch case:

The switch case is used when needed when a condition needs several satisfaction and for each, there is a block of code needs to execute. It also can be said switch is used for multiple time used if condition.

Suppose color if the color is red show some picture else if the color is blue show another else if the color is green show some other and so on

Example:

 var color:string = "Red"; 
switch(color) {
case "Red": {
console.log("The chosen color is Red");
break;
}
case "Green": {
console.log("The chosen color is Green");
break;
}
case "Blue": {
console.log("The chosen color is Blue");
break;
}
default: {
console.log("Invalid choice");
break;
}
}

Share The Post On -