Home  >  Article  >  Web Front-end  >  Switch Case Statement

Switch Case Statement

王林
王林Original
2024-07-27 00:01:14536browse

Switch Case Statement

Switch case statements are an efficient way to execute different blocks of code based on various conditions. It's like a more structured and readable if-else.

Basic Syntax

switch (expression) {
  case value1:
    // kode untuk value1
    break;
  case value2:
    // kode untuk value2
    break;
  // tambahkan lebih banyak case sesuai kebutuhan
  default:
    // kode jika tidak ada case yang cocok
}

How it Works

  • Expression is evaluated once.
  • The value of the expression is compared for each case.
  • If there is a match, the code block in that case is executed.
  • Break is used to stop execution after finding a match.
  • Default is optional and will be executed if no case matches.

Practical Example
Suppose we want to provide different messages based on the value of a variable day:

let day = 3;
let dayName;

switch (day) {
  case 1:
    dayName = "Senin";
    break;
  case 2:
    dayName = "Selasa";
    break;
  case 3:
    dayName = "Rabu";
    break;
  case 4:
    dayName = "Kamis";
    break;
  case 5:
    dayName = "Jumat";
    break;
  case 6:
    dayName = "Sabtu";
    break;
  case 7:
    dayName = "Minggu";
    break;
  default:
    dayName = "Hari tidak valid";
}

console.log(dayName); // Output: Rabu

Tips

  • Use switch case when there are many conditions that need to be checked.
  • Don't forget to add a break to prevent execution from continuing to the next case.
  • Default is useful for handling unexpected values.

Switch case makes the code cleaner and easier to understand compared to long if-elses. Try it in your projects and see the difference!

The above is the detailed content of Switch Case Statement. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn