07 Switch Case

Here are five examples of `switch` statements in JavaScript, ranging from easy to hard, with output displayed directly in the browser using `document.write`.


 

---


 

### 1. **Basic Switch Case** - Easy
```javascript
document.write("<h3>Basic Switch Case</h3>");
let day = 2;
switch (day) {
    case 1:
        document.write("Monday");
        break;
    case 2:
        document.write("Tuesday");
        break;
    case 3:
        document.write("Wednesday");
        break;
    default:
        document.write("Invalid day");
}
```


 

---


 

### 2. **Switch with Multiple Cases** - Easy
```javascript
document.write("<h3>Switch with Multiple Cases</h3>");
let fruit = "apple";
switch (fruit) {
    case "apple":
    case "pear":
        document.write("This is a pome fruit.");
        break;
    case "banana":
    case "mango":
        document.write("This is a tropical fruit.");
        break;
    default:
        document.write("Unknown fruit.");
}
```


 

---


 

### 3. **Switch with Number Ranges (Approximation)** - Medium
```javascript
document.write("<h3>Switch with Number Ranges</h3>");
let score = 85;
switch (true) {
    case (score >= 90):
        document.write("Grade: A");
        break;
    case (score >= 80):
        document.write("Grade: B");
        break;
    case (score >= 70):
        document.write("Grade: C");
        break;
    case (score >= 60):
        document.write("Grade: D");
        break;
    default:
        document.write("Grade: F");
}
```


 

---


 

### 4. **Switch with Functions** - Medium
```javascript
document.write("<h3>Switch with Functions</h3>");
function getDayName(dayNumber) {
    switch (dayNumber) {
        case 1: return "Sunday";
        case 2: return "Monday";
        case 3: return "Tuesday";
        case 4: return "Wednesday";
        case 5: return "Thursday";
        case 6: return "Friday";
        case 7: return "Saturday";
        default: return "Invalid day number";
    }
}
document.write("Day: " + getDayName(5));
```


 

---


 

### 5. **Switch with Default Logic** - Hard
```javascript
document.write("<h3>Switch with Default Logic</h3>");
let userRole = "editor";
switch (userRole) {
    case "admin":
        document.write("Welcome Admin! You have full access.");
        break;
    case "editor":
        document.write("Welcome Editor! You can edit content.");
        break;
    case "viewer":
        document.write("Welcome Viewer! You can only view content.");
        break;
    default:
        document.write("Unknown role. Access denied.");
}
```


 

---


 

Copy and paste these examples into an HTML file to see them displayed in your browser! 😊
3 min read
Nov 19, 2024
By Md Real
Share

Leave a comment

Your email address will not be published. Required fields are marked *