Conditional statements in javascript (if, else if, else, switch)
In JavaScript, conditional statements are used to perform different actions based on different conditions.
1. if Statement
The if
statement executes a block of code if a specified condition is true.
let age = 18;if (age >= 18) {console.log("You are an adult.");}
2. else Statement
The else
statement executes a block of code if the condition in the if
statement is false.
let age = 16;if (age >= 18) {console.log("You are an adult.");} else {console.log("You are a minor.");}
3. else if Statement
The else if
statement specifies a new condition to test if the first condition is false.
let age = 20;if (age < 13) {console.log("You are a child.");} else if (age >= 13 && age < 18) {console.log("You are a teenager.");} else {console.log("You are an adult.");}
4. switch Statement
The switch
statement evaluates an expression, matches the expression's value to a case
clause, and executes the associated block of code.
let day = 3;switch (day) {case 1:console.log("Monday");break;case 2:console.log("Tuesday");break;case 3:console.log("Wednesday");break;case 4:console.log("Thursday");break;case 5:console.log("Friday");break;case 6:console.log("Saturday");break;case 7:console.log("Sunday");break;default:console.log("Invalid day");}
Summary
if
: Checks if a condition is true, and executes a block of code.else
: Provides an alternative block of code if theif
condition is false.else if
: Allows testing multiple conditions.switch
: Compares an expression to multiple possible values (cases) and executes code for the matching case.