this is way to to run the statements based on condition it satisfy.
there are few way of implementing this.
1. If block: it will evaluate the boolean expression, if true, it will run the block statements inside it else it will skip.
Syntax
1 2 3 |
if (boolean expression) { // statement will execute if the boolean expression is true } |
example code:
1 2 3 4 5 |
//if statement var flag:boolean=true; if(flag) { console.log("success") //print success } |
2. if else : it will evaluate the expression to boolean. expression is true, then run the if block. expression false, run the else block.
syntax:
1 2 3 4 5 |
if(boolean_expression) { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false } |
example code:
1 2 3 4 5 6 7 |
//if else statement var flag: boolean = false; if (flag) { console.log("success") } else { console.log("fail"); //print fail } |
3. else if : it will evaluate all the expression until find one true expression and execute respective block statements. if all expression are false, it will execute the else statements.
syntax:
1 2 3 4 5 6 7 |
if (boolean_expression1) { //statements execute if the expression1 evaluates to true } else if (boolean_expression2) { //statements execute if the expression2 evaluates to true } else { //statements execute if both expression1 and expression2 result to false } |
example code:
1 2 3 4 5 6 7 8 9 |
//else if statement var day: string = "Sunday"; if (day == "Monday") { console.log("Monday") } else if (day == "Sunday") { console.log("Sunday") // print Sunday } else { console.log("Some other day") } |
4. Switch: It will compare variable expression to every case. whichever case matched , it will execute the respective statements.
Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
switch(variable_expression) { case constant: { //statements; break; } case constant: { //statements; break; } default: { //statements; break; } } |
example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//switch case var grade: string = "B"; switch (grade) { case "A": { console.log("Excellent"); break; } case "B": { console.log("Good"); //print B break; } case "C": { console.log("Fair"); break; } default: { console.log("Invalid choice"); break; } } |