JavaScript Conditional Statements
JavaScript conditional statements are used to execute a block of code based on a specific condition.
if statement
The if statement executes a block of code if a specified condition is true.
if (condition) {
// code to be executed if condition is true
}
// example
let age = 10;
if (age < 18) {
console.log("Person is a child");
}
if-else
A separate block of code can be executed if the condition is false:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
// example
let age = 10;
if (age < 18) {
console.log("Person is a child");
} else {
console.log("Person is an adult");
}
if-else-if
if-else
statements can be "chained" to satisfy multiple conditions:
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 age = 10;
if (age < 13) {
console.log("Person is a child");
} else if (age < 18) {
console.log("Person is a teenager");
} else {
console.log("Person is an adult");
}
Switch statement
The switch
statement is used to select one of many code blocks to be executed. It provides a more efficient way to handle multiple options in your code.
switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
// other cases here
// ...
default:
// code to be executed if expression doesn't match any of the cases
}
Here is an example of computing weekdays and weekend via switch
- notice that case
's without a break
statement simple "fall-through" to the next case
:
let day = "Sunday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Today is weekday");
break;
case "Saturday":
case "Sunday":
console.log("Today is weekend");
break;
default:
console.log("Invalid day");
}
// prints: "Today is weekend"