In what scenarios would implementing the JS Switch case statement be more efficient than using numerous If/Else statements?

Greetings and thank you in advance for any help or guidance.

I am currently developing a Space Battle game and I am curious to know if there is a way to utilize a JavaScript SWITCH case statement to streamline the numerous If/Else statements that are currently in my code.
I am unsure where to start with the switch (expression).
Would it be appropriate to implement a switch (expression) in this program?

// Implementing the Battle Function to manage the battle process

let shipsBattle = (ship1, ship2) => {

  let ships = [ship1, ship2]; // storing the ships in an array
  let attack = false;
  let attacking = 0;
  let beingAttacked = 1;
  let temp;
  console.log("%c Attack Begins =================", "font-size: 30px");
  while (ships[beingAttacked].hull > 0) { //Keep attacking as long as the hull is above 0


    // Execution of the attack

    if (ships[beingAttacked].hull > 0) {

      console.log("\n"); // Display attack information on the console
      console.log(
        `%c ${ships[attacking].name} attacked ${ships[beingAttacked].name}`,
        "color: purple; border: 1px solid grey; font-size: 18px;"
      );

      attack = ships[attacking].attack(); // Initiate attack on enemy ship
      if (attack === true) {
        ships[beingAttacked].hull -= ships[attacking].firePower; //Increase Fire power
        console.log(
          `%c Attack Successful! ${ships[beingAttacked].name} Hull: ${ships[beingAttacked].hull}`,
          "color: green; font-weight: bold; font-size: 16px;"
        );
      } else {
        console.log(
          `%c Attack Unsuccessful! ${ships[beingAttacked].name} Hull: ${ships[beingAttacked].hull}`,
          "color: red; font-size: 16px;"
        );
      }

      if (ships[beingAttacked].hull <= 0) { // Verify if the ship being attacked is destroyed
        console.log(
          `%c ${ships[beingAttacked].name} has been destroyed`,
          "color: red; border: 1px solid grey; font-size: 16px;"
        );
        if (ships[beingAttacked] === ussSchwartz) {

          alert("Game Over!!!"); //Notify player of Game Over when USS Ship is destroyed
        } else if (
          ships[beingAttacked].name === alienShips[alienShips.length - 1].name
        ) {
          alert(
            `%c ${ships[beingAttacked].name} destroyed!\nAlien fleet has been destroyed!\nyou have been victorious`,
            "color: green;"
          );
        } //Inform player of victory if USS destroys alien fleet
        else {
          game.userResponse = prompt(
            `${alienShips[game.targetShip].name} destroyed!!\n${
              ussSchwartz.name
            } Hull: ${
              ussSchwartz.hull
            }\nWould you like to ATTACK the next ship or RETREAT from battle?`,
            ""
          );
          game.targetShip += 1; //Prompt player to continue or retreat
          checkUserPrompt();
          return;
        }
      } else {

        temp = attacking; // Switch attacking/attacked ships
        attacking = beingAttacked;
        beingAttacked = temp;
      }
    }
  }
};

Answer №1

Upon my inspection, it appears you are verifying ships[beingAttacked].hull > 0 and then performing computations involving true and false values. Following this, you are modifying ships[beingAttacked] and conducting comparisons with ships[beingAttacked].hull < 0

Considering this, the use of a switch statement seems misplaced as it is typically employed when there are predefined conditions and different comparisons are not made within each else if statement.

It seems like you may be aiming to streamline your code. I would recommend the following steps:

  • Construct a flow chart outlining your various scenarios and identify any shared code or reusable logic.
  • Refactor that code into separate functions to enhance readability and facilitate code reuse.

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

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

What is the benefit of using $q.all() with a single promise in AngularJS?

As I delve into this codebase, one snippet keeps popping up: $q.all([promise]).then(responseFunc); However, I find this confusing. After reading the documentation, I wonder why not simply use the following, as it's just a single promise... promise. ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

Is there a way to deactivate a button upon clicking and then substitute it with a new button that serves a different purpose in AngularJS?

Is there a way to deactivate a button once clicked and substitute it with another button that performs a different task using AngularJS? Here is the button in question: <button type="submit" class="btn btn-small btn-default" ng-disabled="isteam==0 || ...

Leveraging the const keyword within a for loop

Imagine having the following snippet of code: for (let i=0; i<1000; i++) { //Retrieve row from MongoDB **const** foo = Collection.find({index:i}); } vs for (let i=0; i<1000; i++) { //Retrieve row from MongoDB **let** foo = Collection ...

Highlight react-bootstrap NavItems with a underline on scroll in React

I am currently working on a website where I have implemented a react-bootstrap navbar with several Nav items. My goal is to enable smooth scrolling through the page, where each section corresponds to an underlined NavItem in the navbar or when clicked, aut ...

What is the process for including an item in an array within Firestore?

Can someone help me with this code snippet I'm working on: await firebase.firestore().doc(`documents/${documentData.id}`).update({ predictionHistory: firebase.firestore.FieldValue.arrayUnion(...[predictions]) }); The predictions variable is an ar ...

Getting a pair of values from an enumeration array

I am currently working on a Java coding exercise that involves creating a list using an enum command. In this exercise, I need to prompt the user for a color input and then return specific example values based on the color entered. The variable names have ...

Extract individual export icons from the React icon library

I've recently put together an icon package and am ready to share it with the world under the name @rct/icons. Here's a glimpse at my package.json: { "name": "@rct/icons", "version": "1.0.0", "sc ...

The issue of Vue.js template errors within inline code

I am experimenting with using inline-template in combination with vue.js 2.0. This usage is within the context of Laravel blade 5.4: <users inline-template> <tbody> @foreach($users as $user) <tr> ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

There are various iterations of html2canvas available

After upgrading html2canvas from v0.5.0 to v1.0.0, a specific function ceased to work on iOS. Therefore, I am interested in utilizing v0.5.0 on iOS and v1.0.0 on other devices. Is there a way to incorporate and switch between both versions of html2canvas ...

Is it possible to modify a single value in a React useState holding an object while assigning a new value to the others?

In my current state, I have the following setup: const [clickColumn, setClickColumn] = useState({ name: 0, tasks: 0, partner: 0, riskFactor: 0, legalForm: 0, foundationYear: 0 }) Consider this scenario where I only want to update ...

Eliminate HTML TAG entries from the input form

My issue is that when I try to type a comma, it does not allow me to do so. How can I add other characters like <, >, /, \, etc? $("#in1").keypress(function (evt) { if (String.fromCharCode(evt.which) == ",") return false; }); < ...

When a timeout is triggered, the AngularJS Promise is not being cancelled

In my endeavor to incorporate a simple timeout feature into my promise, I set out with the intention that if I do not receive a response within 1 second, the request should be terminated. The code should not hang for a response nor execute any code intende ...

Newbie's guide: Saving information in Ruby on Rails

In my Rails 4 application, I am looking to save questions and answers either in a document or database. Once stored, I want to showcase them on a specific webpage for users to respond. For instance, I envision having a page titled /questions where a quest ...

Changing the name of a React Native sample application

I am currently working on a project based on this App example: https://github.com/aksonov/react-native-router-flux/tree/master/Example When I tried to change the following lines: index.ios.js import App from './App'; AppRegistry.regist ...

Tips for sending a Json array to a servlet

[DUPICATE] Here is the JSON code I am using for my POST request: var data_create = JSON.stringify($("#form_create_delegate").serializeArray()); alert("data_create content" + data_create); // console.log(data_create) $.ajax({ ...

Utilizing state in React to both store and retrieve data

I'm a newcomer to web development, looking to enhance my React skills by creating a simple weather app using the OpenWeatherMap API. My goal is to store the API response in state to avoid multiple calls. useEffect(() => { let API = " ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...