TypeScript - If…else Statement


Advertisements

An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false.

Syntax

if(boolean_expression) {  
   // statement(s) will execute if the boolean expression is true
} else {
   // statement(s) will execute if the boolean expression is false  
}

Flowchart

if else Statement

The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true.

The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.

Example: Simple if…else

var num:number = 12; 
if (num % 2==0) { 
   console.log("Even"); 
} else {
   console.log("Odd"); 
}

On compiling, it will generate the following JavaScript code −

//Generated by typescript 1.8.10
var num = 12;
if (num % 2 == 0) {
   console.log("Even");
} else {
   console.log("Odd");
}

The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code −

Even 
typescript_decision_making.htm

Useful Video Courses


Video

Angular Essentials - Admin App, Typescript, Docker, c3.js

45 Lectures 4 hours

Antonio Papa

Video

NestJs: Modern ways to build APIs with Typescript and NestJs

41 Lectures 7 hours

Haider Malik

Video

Master Typescript : Learn Typescript from scratch

60 Lectures 2.5 hours

Skillbakerystudios

Video

Three.js and TypeScript

77 Lectures 8 hours

Sean Bradley

Video

TypeScript from Scratch: Go from zero to hero in TypeScript

77 Lectures 3.5 hours

TELCOMA Global

Video

Advanced TypeScript: Generic Search, Sorting and Filtering

19 Lectures 3 hours

Christopher Frewin

Advertisements