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

The series in angular-chart is not displayed at the top as shown in the documentation

angular-chart.js provides an example of a bar chart, which can be found here. Using this as a foundation, I made some modifications to the js and markup code like so. HTML <body ng-app="app"> <div class="row"> <div class="col-m ...

Can one showcase a php content using an ajax event?

I’m having trouble asking the right question because I’m not sure what I’m doing. I have a form that includes a default PHP script that creates three different lines: <form method="GET" name="NewDeliveryNote" action="ItemPosts_INSERT.php"> < ...

What could be causing SVG to not render in a NEXTJS project upon deployment on Vercel?

Recently, I created a standout single-page nextJS application that was beautifully styled with Tailwind CSS. One interesting feature I added was incorporating the background of a component called SectionWrapper as an svg file. To achieve this, I crafted a ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

Concealing a division element if there is no content inside of it

As a newcomer to jQuery, I am experimenting with setting up a code that hides a div when the 'innerHTML' is null. However, my attempt using the code below is not working. Can anyone point out where I might be going wrong? if (($("#php-errors").h ...

What is the best way to prevent handleSubmit from triggering a re-render when moved to a different

Just started experimenting with React and ran into an issue that I can't seem to find a solution for anywhere. I have a basic search form that interacts with an API. If an invalid value is returned, it displays an H3 element with an error message lik ...

The alignment of the JQuery Mobile tabs is off

As I work on developing a Cordova app, I've noticed that the tabs on my Android phone display in an unusual way. Here's what they look like: The image above was created in JSFiddle using JQuery 2.1.0 and JQM 1.4.2 selected with the following co ...

Retrieve data using Ajax querying from a specific data source

Currently, I am attempting to construct a custom query using Ajax to interact with PHP/MySQL. Here is what I have so far: Javascript code: var i=2; fetchFromDBPHP("name", "tblperson", "id="+i); function fetchFromDBPHP(column, table, condition) { ...

Retrieving metadata using breeze is taking too long

Using breeze in my MVC 4 application to fetch data from a remote SQL Server database with about 40 entities. Surprisingly, the loading of metadata is taking longer than expected, ranging between 14s and 35s even though the size is just around 600kb. Howev ...

What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'. JavaScr ...

What is causing the error message "TypeError: expressJwt is not a function" to appear? Is there a way to resolve it and fix the issue?

Authentication with JWT in Node.js: const expressJwt = require('express-jwt') function setupAuth() { const secret = process.env.SECRET_KEY return expressJwt({ secret, algorithms: ['HS256'] }) } module.expor ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Adjust the itinerary's color using leaflet-routing-machine

Is there a way to change the color of the itinerary from red to a different color using the Leaflet routing machine library? I need to modify the styles option with the L.Routing.Line, but I'm not sure how to do it. import L from 'leaflet' ...

Tips for navigating to an element with Nightwatch

I am currently using nightwatch for end-to-end testing of my application. One of the tests is failing because it seems unable to scroll to the element that needs to be tested. I am wondering if scrolling is necessary, or if there is another workaround. Her ...

Organizing and managing one-on-one table tennis matches using a customized data structure. Leveraging the power of Vue, JavaScript, and

Seeking advice on the best approach for storing table tennis match data in a web application. I currently have a method in place that works, but I'm open to suggestions for improvement. Here is my current idea: matches: [ { id: 1 datePlayed ...

Angular service providing a subset of resource data

I am currently working with an Angular factory called DogePrice: .factory('DogePrice', ['$resource', function ($resource) { return $resource("https://chain.so/api/v2/get_info/DOGE"); }]) Usually, the API response looks like this: ...

Calculating the total price of items in a shopping cart by multiplying them with the quantity in Vue.js

I am currently working on enhancing the cart system in Vue.js, with a focus on displaying the total sum of product prices calculated by multiplying the price with the quantity. In my previous experience working with PHP, I achieved this calculation using ...

Increase the space below the footer on the Facebook page to allow for an

I recently created a webpage at and noticed that it is adding extra height below the footer on my Facebook page: "" I am seeking assistance on how to remove this additional 21px height below all content in the footer. I have tried various templates but n ...

Order of execution for setImmediate() and setTimeout() callbacks compared to I/O callbacks

In the world of Node.js, the event loop powered by libuv is divided into specific phases. The poll phase is where we wait for I/O tasks to complete before running their associated callbacks. The length of this waiting period is determined by timers, timeou ...