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

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

Converting a JavaScript variable into PHP using ajax: A comprehensive guide

Can someone please help me troubleshoot this code for passing a JavaScript variable to PHP? It doesn't seem to be working properly. I want to extract the value of an ID from JavaScript and send it over to PHP. <!DOCTYPE html> <html> ...

Tips on arranging an array based on dates and data in JavaScript?

I have an array with dates and other data that I need to sort based on the dates. I'm unsure of how to go about this. Can someone please assist me? Here is the array in question: 0:{_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Data is not being displayed in the Angular table

Currently, I am working on developing a time tracking application as part of a project. However, I have encountered an issue while attempting to showcase all the entries in a table format (as shown in the image below). Despite having two entries according ...

The server sends a response with a MIME type that is not for JavaScript, it is empty

I am trying to integrate an angular application with cordova. Upon running "cordova run android" and inspecting it in Chrome, the console displays the following message: "Failed to load module script: The server responded with a non-JavaScript MIME t ...

Numerous references embedded within a Vue.js component

I am currently working with multiple instances of a polygonCrop component in Vue.js, each one having a unique reference to a canvas property. These components are utilized in separate crop functions triggered by button clicks. My question is how to effecti ...

Ways to retrieve the identifiers of every child node UL element within a UL container

I am struggling with a basic question related to HTML structure. Here is the code snippet I am working with: <ul> <li> <ul class=t2 id=15> <li class='item'>a<span class='val'>b</ ...

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

Node.js encountered an error due to a self-signed certificate within the certificate chain

I'm encountering an issue with client-side HTTPS requests. An example snippet is as follows: var fs = require('fs'); var https = require('https'); var options = { hostname: 'example.com', port: 443, path: & ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

USDC to ETH Swap on Uniswap

Every time I try to swap USDC for ETH using Uniswap and Ethers, I keep encountering errors. async function swapUsdcToEth(amount, walletAddress) { const usdc = await Fetcher.fetchTokenData(chainId, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'); ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

Tips for altering the color of a specific bar in the Material UI BarChart component

I have implemented the following code to generate a Graph: const namesArray = Object.values(tableData).map(item => item.name); const valuesArray = Object.values(tableData).map(item => item.value); return ( <Box> <SimpleCard ti ...

What is the process for altering the active status in pagination?

How can I make the active class in my pagination appear in red? Here's the code snippet I have: In my script.js file: $(".pagination").append("<li class='page-item' id='previous-page'><a class='page-li ...

Display error page when unable to load ng-view template

Is there a way to display a standard error page or template if a certain template cannot be loaded using ngRoute in Angular? I've come across suggestions that subscribing to the $routeChangeError event might help, but I'm not sure what steps to ...