In this tutorial you will learn how to write conditional logic like if else in typescript with different operators, typescript switch case example.
Typescript syntax is very similar to javscript, almost same, so if you are already familiar with JavaScript, then you won’t find much difference.
Like all other programming language we also can write if-else conditional logic in typescript, typescript if else statement is very similar to JavaScript or C#.
So here we learn how to write conditional logic using Comparison Operators in TypeScript
if (condition) { // execute code logic } let speed: number = 10; if (speed >= 50) { console.log("you are at right speed") }
TypeScript If Else example, here i am checking if speed is more than specified number.
let speed: number = 10; if (speed >= 50) { console.log("you are at right speed") } else { console.log("you must speed up now") }
The switch statement evaluates an expression, when we have multiple conditions to check for one variable, switch is the best statement, it finds the matching expression’s value to a case clause, and executes statements associated with that case.
switch(expression value) { case match1: { //statements; break; } case match2: { //statements; break; } default: { //statements; break; } }
Quick overview of switch case statement
var datetime = new DateTime(); var TodayDay = datetime.Day; switch (TodayDay) { case 6: case 0: console.log("Saturday Sunday, Holiday time"); break; case 1: console.log("Monday, Have great week ahead"); break; case 2: case 3: case 4: console.log("Working day."); break; case 5: console.log("Relax, Fun Friday"); break; }
Typescript comparison operators are also same as javascript operators.
==
let varA = 100; let varB = 90; console.log(varA == varB); //false
===
let varA = 100; let varB = 90; console.log( varA === varB ); //false console.log( varA === 10 ); //true
!=
let varA = 100; let varB = 90; console.log( varA != varB ); //true
!==
let varA = 100; let varB = 90; console.log( varA !== varB ); //true
>
let varA = 100; let varB = 90; console.log( varA > varB ); //true
<
let varA = 100; let varB = 90; console.log( varA < varB ); //false
>=
let varA = 100; let varB = 90; console.log( varA >= varB ); //true
<=
let varA = 100; let varB = 90; console.log( varA <= varB ); //false
In all above examples we have used different operators, so you learn how to use the them in typescript coding.
You may be interested to read following posts: