JavaScript Conditional Statements
Conditional statements in JavaScript are used to perform different actions based on different conditions. Here are the main types of conditional statements:
1. if
Statement
Syntax
if(condition){
// code to be executed if condition is true
}
Example
let age = 20;
if (age >=
18) {
console.
log(
“You are an adult.”);
// Output: You are an adult.}
2. if...else
Statement
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example
let age = 16;
if (age >= 18) {
console.log(“You are an adult.”);
} else {
console.log(“You are a minor.”); // Output: You are a minor.
}
3. if...else if...else
Statement
Syntax
if (condition1) {
// code to be executed if condition1 is true}
else
if (condition2) {
// code to be executed if condition2 is true}
else {
// code to be executed if all conditions are false
}
Example
let score = 85;
if (score >= 90) {
console.log(“Grade: A”);
} else if (score >= 80) {
console.log(“Grade: B”); // Output: Grade: B
} else if (score >= 70) {
console.log(“Grade: C”);
} else if (score >= 60) {
console.log(“Grade: D”);
} else {
console.log(“Grade: F”);
}
4. switch
Statement
switch (expression) {
case
value1:
// code to be executed if expression === value1
break;
case
value2:
// code to be executed if expression === value2
break;
// more cases…
default:
// code to be executed if no cases match}
Example
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = “Monday”;
break;
case 2:
dayName = “Tuesday”;
break;
case 3:
dayName = “Wednesday”; // Output: Wednesday
break;
case 4:
dayName = “Thursday”;
break;
case 5:
dayName = “Friday”;
break;
case 6:
dayName = “Saturday”;
break;
case 7:
dayName = “Sunday”;
break;
default:
dayName = “Invalid day”;
}
console.log(dayName);
Syntaxcondition ? expressionIfTrue : expressionIfFalse;
Example
let age = 20;
let status = (age >= 18) ? “adult” : “minor”;
console.log(status); // Output: adult