Conditional Statements

Conditional Statements

Conditional statements in JavaScript are used to make decisions in your code based on certain conditions. These statements allow you to control the flow of your program, executing different blocks of code depending on whether a specified condition evaluates to true or false. There are primarily three types of conditional statements in JavaScript: if, else if, and else.

if statement

  •  The basic if statement is used to execute a block of code if a specified condition is true.
  • The syntax is as follows:
javascript
   if (condition) {
      // Code to be executed if the condition is true
   }
Example
javascript
  let age = 25;

  if (age >= 18) {
      console.log("You are an adult.");
  }  

 In this example, the code inside the curly braces will be executed only if the condition age >= 18 is true.

if-else statement

  • The if-else statement extends the if statement by providing an alternative block of code to execute if the condition is false. The syntax is:
javascript
  if (condition) {
       // Code to be executed if the condition is true
   } else {
      // Code to be executed if the condition is false
   }
Example
javascript
  let age = 15;

  if (age >= 18) {
      console.log("You are an adult.");
  } else {
      console.log("You are a minor.");
  }

In this case, if the condition age >= 18 is false, the code inside the else block will be executed.

if-else if-else statement

  • This structure allows you to test multiple conditions and execute different code blocks based on the first condition that is true. The syntax is:
javascript
  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 no conditions are true
  }
Example
javascript
  let score = 75;
  
  if (score >= 90) {
      console.log("A");
  } else if (score >= 80) {
      console.log("B");
  } else if (score >= 70) {
      console.log("C");
  } else {
      console.log("F");
  }

Leave a Comment