JavaScript Conditional Statements: If/Else and Switch
Learn how to use conditional statements in JavaScript to control the flow of your program.
Introduction to JavaScript Conditional Statements
Conditional statements are used to control the flow of a program based on certain conditions. In this tutorial, we will cover the basics of JavaScript conditional statements.
If/Else Statements
The if statement is used to execute a block of code if a certain condition is true. The else statement is used to execute a block of code if the condition is false. Here is an example of how to use an if/else statement:
let age = 25;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are a minor.');
}
Switch Statements
The switch statement is used to execute a block of code based on the value of a variable. Here is an example of how to use a switch statement:
let day = 'Monday';
switch (day) {
case 'Monday':
console.log('Today is Monday.');
break;
case 'Tuesday':
console.log('Today is Tuesday.');
break;
default:
console.log('Today is not Monday or Tuesday.');
}
Conclusion
In this tutorial, we covered the basics of JavaScript conditional statements. We learned how to use if/else statements and switch statements to control the flow of a program.