The JS if-else statement is used to execute the code based on the given conditions. There are three types of if statements.
- If statements
- If ... else statements
- If ... elseif statements
The JavaScript If statement executes the code when only if the condition is true.
Syntax of if statement
if(expression){
Statements
}
Example
<html> <body> <script> let x=10; if (x>8) { document.write("The value of x is greater than 8"); } </script> </body> </html>
2) JavaScript If-else statement
JavaScript if-else statement evaluates whether the condition is true or false. If the condition is true it executes the if code(Statement 1) or If false it executes the else code(Statement 2).
Syntax of if-else statement
if (expression) { //ifcode(statement 1) to be evaluated if condition is true } else{ //elsecode(statement 2) to be evaluated if condition is false }
Example
<html> <body> <script> var x=10; var y=15; if (x>y) { document.write("x is greater than y"); } else{ document.write("x is less than y"); } </script> </body> </html>
3) JavaScript If-else if statement
JavaScript if-else if statement evaluates whether the first condition is true or false. If the condition is true it executes the if code otherwise jumps to the next else if condition and evaluates it until the condition will be true or until it gets the else statement.
Syntax of if-elseif statement
if (condition1) { //statement to be excuted if condition 1 is true } else if (condition2) { //statement to be excuted if condition1 is false and condition2 is true }else if (condition3) { //statement to be excuted if condition1 and 2 are false and condition3 is true }else{ //statement to be excuted if condition1,2 and 3 are false }
Example
<!DOCTYPE html> <html> <head> </head> <body> <script> var x=10; var y=15; if (x>y) { document.write("x is greater than y"); } else if (x==y) { document.write("x and y are equal"); }else if (x===y) { document.write("x and y are identical"); }else{ document.write("x is less than y"); } </script> </body> </html>
0 Comments