Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to if statements.

For example:

<script>
var textInput = input.value;

switch (textInput) {
case "orange":
    text = "You decided to eat an orange. Do you want to eat another fruit?";
}
document.getElementById("message").innerHTML = text;

</script>

If I wanted to include a response based on whether the user types 'yes' or 'no' after being asked about eating another fruit, how could I add that condition inside the same case?

Is it possible to achieve something like that with switch statements? I hope my question makes sense.

Thank you for your assistance!

Answer №1

Feel free to include any regular code within the case block, enabling you to incorporate if statements:

switch (textInput) {
case "orange":
    if (some_other_condition) {
        text = "You've chosen to have an orange. Would you like to try another fruit?";
    } else {
        text = "Okay, that's the final fruit";
    }
    break;
    ...
}

Answer №2

As long as the case remains intact, the switch statement will be executed without interruption.

switch (textInput) {
  case "orange":
    text = "You have chosen to consume an orange. Would you like to try another fruit?";
    // break; this line is commented out so we do not break from this case
  case "fruit":
    text = "You have decided to eat a piece of fruit?";
    break;
}

If textInput is either orange or fruit, the value

You have decided to eat a piece of fruit?
will be assigned to text.

This technique allows for combining certain scenarios to some extent, however, it is strongly discouraged due to various complexities.

Answer №3

Here is an example of a way to achieve something like this, although it's not typically recommended:

function compareNumbers(num1, num2) {
     switch (true) {
        case num1 > num2:
                    console.log(num1 + " is larger than " + num2);
                    break;
        case num1 < num2:
                    console.log(num2 + " is larger than " + num1);
                    break;
        default:
                    console.log(num1 + " is equal to " + num2);
      }
   }
   
   compareNumbers(5,6);

Answer №4

Aha! It's absolutely possible to include If conditions within a switch statement. Give it a shot and see the magic happen right here.

switch (true) {
    case (dog === 'pet' && cat === 'pet'):
        // perform this action
        break;
    case (foo === 'bar'):
        // take an alternate route
        break;
    default:
        // text = "How about trying out an apple instead of that orange?";
}

Answer №5

Definitely! Enhancing your code:

<script>
var userInput = input.value;

switch (userInput) {
case "orange":
    outputText = "You chose to eat an orange. Do you feel like having another fruit?";
    break;
case "banana":
    outputText = "Enjoyed a banana today";
    break;
case default: // If the input doesn't match any case
    outputText : ""; // No action taken per OP's request
    break;
}
document.getElementById("message").innerHTML = outputText;

</script>

For further information, please visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Answer №6

It's worth mentioning that switch statements do not support conditions in the traditional sense. Instead, they primarily serve to handle different cases or states of a variable.

If you're looking to incorporate conditions into your logic, you might consider structuring it differently. One approach could be:

var addMore = true;
while(addMore){
 var textInput = prompt("Select your fruit");
 switch (textInput) {
  case "orange":
   addMore = confirm("You decided to eat an orange. Do you want to eat another fruit?"); // Consider using a yes or no question
  default:
    addMore = false;
  }
 }

Alternatively, if you're working with a user interface, utilizing components like checkboxes might offer a more intuitive solution for handling multiple inputs.

I hope this suggestion proves helpful!

Answer №7

To streamline the process of looping until a termination string is entered, you can incorporate the switch statement within a do-while loop. This eliminates the need for multiple conditions within each switch statement.

Give it a try:

var text = "Choose a color: blue, red, green or stop to end";
var colorsChosen = [];

do {
  var inputColor = prompt(text);
  
  switch (inputColor) {
    case "red":
      colorsChosen.push("red");
      text = "You chose red. Pick another color: blue, red, green or stop to end";
      break;
    case "blue":
      colorsChosen.push("blue");
      text = "You chose blue. Pick another color: blue, red, green or stop to end";
      break;
    case "green":
      colorsChosen.push("green");
      text = "You chose green. Pick another color: blue, red, green or stop to end";
      break;
    default:
      text = "Invalid choice.\n\nChoose a color: blue, red, green or stop to end";
      break;
  }
} while(inputColor !== "stop");

var messageText = "Colors chosen: ";
for(var j=0; j<colorsChosen.length; j++) {
  messageText += colorsChosen[j];
  if(j != colorsChosen.length-1)
    messageText += ", ";
}
document.getElementById("result").innerHTML = messageText;
<div id="result"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The delete button in the "Chip" component of React Material-UI is not functioning as expected

I'm having trouble with the "Chip" control and its "X" button functionality. Unlike the examples shown here: http://www.material-ui.com/#/components/chip Adding the "onRequestDelete" property does include the "X" button, but it doesn't respond t ...

Updating Angular Material theme variables during the build processIs this okay?

How can I easily customize the primary color of my angular 6 application to be different for development and production builds? Is there a simple solution to automatically change the primary color based on the build? ...

Is it necessary for me to install node and npm in order to use bower, even if I am not a node programmer?

As a Java programmer focusing on a web application, I'm finding that managing JavaScript can be quite challenging. I recently discovered Bower, a JavaScript dependency manager, but found out that it requires both Node and npm to be installed first. ...

Angular directive for resizing C3 charts

I've recently implemented a basic donut chart using C3, which I've enclosed in a directive and everything is functioning smoothly. Below is the code for my directive: angular.module('dashboardApp').directive('donutChart', fu ...

Tips for extracting parameters from a URL using Express JS in a custom manner

Recently, I set up a server using the express package and encountered an issue while trying to extract parameters from the URL in a specific format. The URL structure is as follows: (notice there's no '?' indicating parameters). I am lookin ...

Can Vue.js automatically refresh the display when there are changes in a third-party JSON file?

I'm attempting to achieve a specific goal using Vue, but I'm uncertain if it's feasible given my current struggles in obtaining the desired outcome: An API endpoint returns an array containing multiple objects. While I am able to successfu ...

Issue with ISO-8859-1 character encoding in table formatting

I have set my website to use ISO-8859-1 encoding and special characters are displaying correctly. However, I'm facing an issue with the datatables plugin which does not seem to recognize special characters in the table data. Do I need to configure an ...

Issue: Module 'js' not found in Node.js Express application

I am currently working on a NodeJS express application. While developing, I encountered the following issue: Error: Cannot find module 'js' After researching online, I couldn't find a solution. The typical troubleshooting steps didn&ap ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

What is the best way to retrieve a JSP parameter dynamically or how can one create a JSP parameter on the

Currently learning JSP and ajax simultaneously. In the process of creating a dynamic tab that can be added or removed using these steps. Looking to pass parameters from controller to the content area of the newly added tab. 1. When clicking on the &apos ...

Creating a Yup field that is an object and making it required when another field is set to true in the validation process

Just getting started with Yup validation and I'm facing an issue. I am attempting to make certain fields required based on a condition. Specifically, I want the digital object to be required only if hasDigital is true; otherwise, it should be optional ...

Tips for assigning data from an AJAX response to a variable

Using jQuery and the code provided, there seems to be an issue with variable scope when some_condition is false. The error "items is not defined" indicates this problem. The goal is to set the result variable to the AJAX response data in order to use it o ...

Dividing a JSON array by a specific key using lodash underscore

I'm on a quest to extract the distinct items in every column of a JSON array. Here is what I aim to convert : var items = [ {"name": "Type 1","id": 13}, {"name": "Type 2","id": 14}, {"name": "Type 3","id": 14}, {"name": "Type 3","id": 13}, {"na ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Tips for concealing the Bottom bar action in React Native

Currently facing an issue with React Native - I need to hide the bottom action bar located just below my tab bar navigation. I'm trying to create a clone of the Disney + App and this particular problem has me stuck: Here's the bottom part of my ...

When trying to access $model.show() in Vue.js, the returned model is showing as undefined

I'm running into a console error message every time I try to click the button for $model.show('demo-login'): TypeError: Cannot read property 'show' of undefined Error output when the button is clicked: TypeError: Cannot read prop ...

Clicking on a link in HTML with the onclick event

I am looking to create a button that will direct me to a different page. Here is the code snippet I have: <div align="right" ><input type="submit" id="logout" onclick="location.href='/login?dis=yes'" value="Sign Out" ></div>& ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Experiencing difficulties with JavaScript/jQuery when encountering the 'use strict' error

I have been working on a small function to change the background of an HTML file, but I keep getting the 'Missing 'use strict' statement' error message from JSLint despite trying multiple solutions. Can anyone suggest how to resolve th ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...