MakeW3web

JavaScript Conditional Statements

Conditional statements in JavaScript are used to make decisions based on certain conditions. They allow you to execute different code blocks depending on whether a given condition is true or false. The most common conditional statements in JavaScript are `if`, `if-else`, `if-else-if`, and `switch`.

  1. `if` statement:

The `if` statement evaluates a condition and, if the condition is true, it executes the code block inside the statement.

const age = 18;

if (age >= 18) {
  console.log("You are eligible to vote.");
}
  1. `if-else` statement:

The `if-else` statement evaluates a condition and, if the condition is true, it executes the first code block; if the condition is false, it executes the second code block.

const age = 16;

if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not eligible to vote.");
}
  1. `if-else-if` statement:

The `if-else-if` statement is used when you need to check multiple conditions in sequence. It evaluates each condition one by one, and if a condition is true, it executes the corresponding code block and skips the remaining conditions.

const grade = 75;

if (grade >= 90) {
  console.log("A");
} else if (grade >= 80) {
  console.log("B");
} else if (grade >= 70) {
  console.log("C");
} else if (grade >= 60) {
  console.log("D");
} else {
  console.log("F");
}
  1. `switch` statement:

The `switch` statement is an alternative to the `if-else-if` statement when you have a large number of conditions to check. The `switch` statement evaluates an expression and compares its value to different cases. If a matching case is found, the corresponding code block is executed.

const day = 3;
let dayName;

switch (day) {
  case 0:
    dayName = "Sunday";
    break;
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  default:
    dayName = "Invalid day number";
}

console.log(dayName); // "Wednesday"

Understanding and using conditional statements is essential for creating dynamic and responsive JavaScript code. They allow you to execute different code blocks depending on the outcome of specific conditions, giving you control over the flow of your program.

Was this page helpful?