Home > Article > Web Front-end > 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
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
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!