JAVASCRIPT Tutorial

Switch Statement

Introduction:

A switch statement provides an efficient way to handle multiple conditions by comparing a value against a series of cases.

Key Concepts:

  • Expression: The value being evaluated.
  • Case: A specific value that the expression is compared against.
  • Default: The code to be executed if the expression doesn't match any case.
  • Break: Used to exit the switch statement after a case has been executed.

Syntax:

switch (expression) {
  case value1:
    // Code to be executed if expression = value1
    break;
  case value2:
    // Code to be executed if expression = value2
    break;
  ...
  default:
    // Code to be executed if expression doesn't match any case
}

Practical Example in JavaScript:

function getSeason(month) {
  switch (month) {
    case 1:
    case 2:
    case 12:
      return "Winter";
    case 3:
    case 4:
    case 5:
      return "Spring";
    case 6:
    case 7:
    case 8:
      return "Summer";
    case 9:
    case 10:
    case 11:
      return "Autumn";
    default:
      return "Invalid month";
  }
}

console.log(getSeason(3)); // Output: Spring

Tips for Use:

  • Use cases to represent specific values.
  • Use the default case for handling cases that don't match any other case.
  • Use breaks to prevent unwanted execution of subsequent cases.
  • Keep switch statements concise and well-organized.