BeginnerCoder
beginner#javascript#conditional statements

JavaScript Conditional Statements: If/Else and Switch

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

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.

Keep going with javascript

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.