I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game.

I've tried everything, including console logging the compare and putting it inside a variable.

Strange enough, console.log(compare) is returning undefined.

If anyone can assist, I would greatly appreciate it.


var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}
console.log("Computer's choice: " + computerChoice);
console.log("Your choice: " + userChoice);
console.log(computerChoice + " vs " + userChoice); 

var compare = function(userChoice, computerChoice) {
    if (userChoice === computerChoice) {
        return "The result is a tie!"; 
    } else if (userChoice === "rock") {
        if (computerChoice === "scissors") {
            return "rock wins!";    
        }
        else {
            return "paper wins!";       
        }
    } else if (userChoice === "paper") {
        if (computerChoice === "rock") {
            return "paper wins!"; 
        }
        else {
            return "scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if (computerChoice === "rock") {
            return "rock wins!"; 
        }
        else {
            return "scissors wins!";
        }
    }
}

Answer №1

let userChoice = prompt("Choose between rock, paper or scissors");
let computerChoice = Math.random();
let result;

if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer chose: " + computerChoice);
  console.log("Your choice: " + userChoice);
  console.log(computerChoice + " vs " + userChoice); 

function compareChoices(userChoice, computerChoice){
    if (userChoice === computerChoice){
        return    "It's a tie!"; 
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
        return "Rock wins!";    
       }
       else {
         return "Paper wins!";       
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
        return "Paper wins!"; 
        }
        else {
        return "Scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
        return "Rock wins!"; 
        }
        else {
        return "Scissors wins!";
        }
    }
     
}
let comparisonResult = compareChoices(userChoice, computerChoice);
console.log(comparisonResult);

Answer №2

An error in syntax has been identified...

return  =  "The outcome is a deadlock!"; 

Please modify it to:

return "The outcome is a deadlock!"; 

Answer №3

Shinra tensei pointed out an issue in line 18 where you had an equal sign causing an error. I have provided an updated snippet below and included an alert for the comparison function.

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer's choice: " + computerChoice);
console.log("Your choice: " + userChoice);
console.log(computerChoice + " vs " + userChoice); 

alert(compare(userChoice,computerChoice));

function compare(userChoice, computerChoice){
    if (userChoice === computerChoice){
        return  "The result is a tie!"; 
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
            return "rock wins!";    
       }
       else {
            return "paper wins!";       
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
            return "paper wins!"; 
        }
        else {
             return "scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
            return "rock wins!"; 
        }
        else {
            return "scissors wins!";
        }
   }   
}

Answer №4

The issue at hand is the failure to execute the anonymous function that was written. I modified it to be a regular function to align more closely with other programming languages. This revised code should work effectively:

var userChoice = prompt("Please select rock, paper, or scissors:");
var computerChoice = Math.random();
var result;

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer chose: " + computerChoice);
  console.log("You chose: " + userChoice);
  console.log(computerChoice + " versus " + userChoice); 


function compare(userChoice, computerChoice){
    if (userChoice === computerChoice){
        return    "It's a tie!"; 
    } else if (userChoice ==="rock"){
       if(computerChoice ==="scissors"){
        return "Rock wins!";    
       }
       else {
         return "Paper wins!";       
       }
    } else if (userChoice === "paper") {
        if(computerChoice === "rock") {
        return "Paper wins!"; 
        }
        else {
        return "Scissors wins!";
        }
    } else if (userChoice === "scissors") {
        if(computerChoice === "rock") {
        return "Rock wins!"; 
        }
        else {
        return "Scissors wins!";
        }
    }

}
console.log(compare(userChoice, computerChoice));

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

`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain. I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3 ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

Having trouble retrieving text from an HTML form in Node.js using express, as the req.body object is coming up

Having trouble extracting text from an HTML form to build a basic text to speech functionality. Despite using an express server, the req.body is consistently empty when attempting to fetch the text. I've experimented with body-parser and adjusted the ...

Material-UI Swipeable Drawer with a see-through design

Any tips on how to apply a 'transparent' style background property to my SwipeableDrawer component from Material UI? I'm having difficulty changing the background directly from my code since the component generates another component in the H ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...

Incorporating dynamic form elements using Vue.js within a targeted div

Here is the HTML and Vue.js code that I have: <table class="table"> <thead> <tr> <td><strong>Title</strong></td> <td><strong>Description< ...

Ways to Toggle div Visibility for Elements with Identical Class Names on an Individual Basis

After searching for solutions on stackoverflow, I attempted to implement some answers provided by other users, but I'm still not achieving the desired outcome. In my website's about section, there are four different items. When a specific item&a ...

Searching for and replacing anchor tag links within a td element can be achieved using PHP

I am currently customizing my WordPress website and I need to update the URL (product link) of the "product-image" on the "cart" page. I have the following dynamic code: <td class="product-name" data-title="Product"> <a href=&q ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

I am experiencing difficulties in initializing a class (controller) in Nextjs version 13

I am working on an application built with Next.js where I have a controller class responsible for handling all the access functions, such as retrieving data from the database. However, I keep encountering this error message: Error [ReferenceError]: Cannot ...

Tips for effectively using the question mark as a separator in a webservice URL

In my nodejs / express project, I am attempting to create a webservice where I separate the URL from parameters using '?' and use '&' as parameter separators. When using this method, it works perfectly fine: app.get("/tableref/:event/ ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () => ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

Having difficulty identifying duplicate sentences in Vue.js when highlighting them

I am looking for a way to identify and highlight repetitive sentences within a text area input paragraph. I attempted the following code, but unfortunately, it did not produce the desired result. highlightRepeatedText(str) { // Split the string into an ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Execute operations on element itself rather than the output of document.getElementbyId

I encountered an issue involving an HTML element with the ID of BaseGridView. When I call a function directly on this element, everything works perfectly. However, if I use document.getElementById() to retrieve the element and then call the function, it do ...

Change the font awesome class when the button is clicked

Here is the code I have in this jsfiddle. I am trying to change the font awesome icon on button click using javascript, but it doesn't seem to be working. I am new to javascript, so please pardon me if this is a silly question. HTML <button id="f ...

Clicking an AngularJS button within a form is causing an unexpected page refresh

I am facing an issue with adding a new input field on click. I have two buttons, one to add and another to remove the input box. When I click on the add button, it should add a set of input boxes, but currently, it only adds one and refreshes the page, dis ...

Displaying data on a monthly basis along the X-axis in Recharts

I need the X Axis to only display the months, while still being able to add content on different days within each month. My attempts to use ticks resulted in the removal of the X Axis. I then tried using ticksFormatter, but it caused the X Axis captions t ...