Switch statements within switch statements

Currently encountering an issue where nothing is showing up. Assistance needed, please...

function getTotal()
{
var service = prompt("What service are you interested in? ", " ");
var options = prompt("How often would you like the service? ", " ");
var contractLength = prompt("How long do you want the contract?" , " ");
var totalPrice = " ";
    switch (service) {
        case 'Lawn Maintenance':
            switch (options) {
                case 'Monthly':
                    switch (contractLength) {
                        case '6':
                            totalPrice = $25 }
                            }
    break; }

Answer №1

Using switch statements, especially when nested, can complicate and obfuscate code. An alternative approach would be to employ an object indexed by options, like the example below:</p>

<pre><code>function getTotal() {
  var service = prompt("What service would you like? ", " ");
  var frequency = prompt("How frequent do you want the service? ", " ");
  var contractLength = prompt("How long do you want the contract?", " ");
  const services = {
    'Lawn Maintenance': {
      'Monthly': {
        '3': 15,
        '6': 25
      },
      'Yearly': {
        '3': 5,
        '6': 10
      }
      // etc
    }
  }
  const serviceObj = services[service];
  if (!serviceObj) throw new Error('Invalid service');
  const frequencyObj = serviceObj[frequency];
  if (!frequencyObj) throw new Error('Invalid frequency');
  const totalPrice = frequencyObj[contractLength];
  if (totalPrice === undefined) throw new Error('Invalid contract length');
  return '$' + totalPrice;
}

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

Tips on removing properties from an object recursively according to their key/value pairs

My current task involves removing specific children of an object based on whether their "size" key is set to 0. To achieve this, I am utilizing the npm package directory-tree to generate a JavaScript object representation of a chosen directory. The stru ...

Testing Tools for AJAX Integration

Searching for AJAX testing resources. Are there any no-cost tools out there for conducting AJAX tests? Edit 2: Besides Firebug, are there any other tools available? ;) ...

Seamless transition between Nuxt/Vue components as they appear and disappear on the page alongside other content

Is there a way to create a smooth transition when showing and hiding grid items on a webpage? Currently, I have a list of grid items with a button that toggles between "see more" and "see less". When the user clicks on "see more", all items are displayed, ...

Implementing this type of route in Vue Router - What are the steps I should take?

I am currently delving into Vue and working on a project that involves creating a Vue application with a side menu for user navigation throughout the website. Utilizing Vue Router, my code structure looks like this: <template> <div id="app ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

Wind - Best practices for managing the status of multiple entities within a single display prior to executing the save changes function

In my system, there are three main entities: Project, Attachment, and Messages. A project can have multiple attachments and messages associated with it. The issue arises on the project detail view, where I display the project's messages and any attac ...

Having trouble with changing text in a link with an onclick event?

When I click on the link, I want the text to change to the second span. However, this functionality is not working. Code var reload = false; $('#change').click(function() { reload = !reload; $('#change').click(function() { ...

A guide to revealing the value of a button or anchor tag using AngularJS

I'm working on a way to show a button or anchor tag value depending on the true or false value returned by my angular variable. Here's a snippet of my code: <a href="#" id="verify">{{userInformation.value}}</a> The userInformation.v ...

Using switch statement upon page loading in AngularJS

I am currently working on refactoring a switch statement that identifies specific classes upon page load into one of my controllers. Does anyone have suggestions on how I can transform this straightforward task using Angular? $('.radior').eac ...

What is the process of making navigation tabs or thumbnails similar to those in Firefox or Google Chrome?

Is there a way to display important links or services on my website as multiple thumbnails or tabs, similar to how Firefox or Google Chrome show the latest opened websites? I have searched for a solution using CSS or JQuery but haven't been able to f ...

A guide to extracting the Jquery Version from the Chrome browser console while browsing webpages and transferring it to the Eclipse Java console using Selenium

Is there a way to retrieve the Jquery Version from Chrome browser console for webpages and transfer it to eclipse Java console using selenium? Try this command: $. ui. version https://i.sstatic.net/3bxA1.png ...

Appending a new element to a JSON object using JavaScript

Hey there, I have a JSON object called departments. When I use console.log(departments) it displays the following data: { _id: 58089a9c86337d1894ae1834, departmentName: 'Software Engineering', clientId: '57ff553e94542e1c2fd41d26', ...

Adjust the text within the paragraph dynamically according to the option chosen in the drop-down menu using

I'm having trouble updating a paragraph in a letter based on the user's selection from a dropdown menu. I can't seem to figure it out. I don't know whether ng-show/hide or ng-options is the best approach for this. I feel completely los ...

Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them. My goal is to check if the body has a specific class and if it does, I want to unc ...

Is it possible to manipulate the response from a MySQL server using Node.js?

For example: The following response represents the original data { "todo_id": 2, "todo_item": "brush your teeth", "scheduled_time": "2020-03-22T07:14:29.000Z", "user_id": 1, "is_done": { "type": "Buffer" ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

I keep running into errors when trying to call functions within a mapped array in my React JS code

During my code execution, I am invoking a function by iterating through an array let artistId = artist._id; orderData.products.map((cartproduct, index) => { const sendOrderData = { product: cartproduct._id, qty: cartproduct.qty, }; ...

What is the process for uploading a file and storing it in a specific directory?

Creating HTML Form for File Upload: <div style="width:200px"> <form action="javascript:_bulkUser();" method="post" enctype="multipart/form-data"> Select File:<input type="file" name="fname"/><br/> <input type="submit ...

How to send configuration data to an external library in Angular 6 in the app.module.ts file

My goal is to provide basic configuration settings to an external or third-party module. These settings are stored in a JSON file for easy modification across different environments without the need to rebuild the code. import { BrowserModule } from &apos ...