I'm having trouble with my Rock Paper Scissors script. The console is showing an error message: "Uncaught SyntaxError: Identifier 'playerSelection' has already been declared."

Currently delving into the world of JavaScript, I've embarked on a project to create a console-based Rock Paper Scissors game. Here's the code snippet that I've come up with:

<!DOCTYPE html>
<html>
<body>
<script>

    let RPS = function playRound (playerSelection, computerSelection) {

    let playerSelection = promt ("What do you choose?", "");

    let computerSelection = math.Random ();
        if computerSelection (<0.34) {
            computerSelection = "Rock";
        } else if computerSelection (>=0.35 && <=0.66) {
                computerSelection = "Paper";
        } else {
                computerSelection = "Scissors";
        }

    if (playerSelection === "Rock"){
        if (computerSelection === "Scissors") {
            console.log ("You win");
        } else {
            console.log ("You lose");
        }
    }    
    if (playerSelection === "Paper") {
        if (computerSelection === "Scissors"){
            console.log ("You win");
        }else {
            console.log ("You lose")
        }    
    }
    if (playerSelection === "Scissors") {
        if (computerSelection ==== "Paper"){
            console.log ("You win")
        } else {
            console.log ("You lose")
        }
    }

    }

</script>
</body>
</html>

However, upon attempting to execute this code in the console, an error is thrown:

Uncaught SyntaxError: Identifier 'playerSelection' has already been declared

I'm puzzled about why this issue is arising. Can anyone shed some light on it?

Answer №1

The mistake here is quite clear. When you pass arguments named playerSelection and computerSelection, you then proceed to declare two local variables with the same names, which leads to duplication. Since arguments are essentially considered as local variables themselves, there is no need to declare them again within the function. Either pass them as arguments or declare new ones inside the function using let, but not both.

Moreover, your code contains several syntax errors that need addressing. It's crucial to thoroughly review your code as even fixing the mentioned issue won't make it operational.

Here is a potential example of what you might be aiming for:

let RPS = function playRound() {
  let playerSelection = prompt("What do you choose?", "");
  let computerSelection = Math.random();

  if (computerSelection < 0.34) {
    computerSelection = "Rock";
  } else if (computerSelection >= 0.35 && computerSelection <= 0.66) {
    computerSelection = "Paper";
  } else {
    computerSelection = "Scissors";
  }

  if (playerSelection === "Rock") {
    if (computerSelection === "Scissors") {
      console.log("You win");
    } else {
      console.log("You lose");
    }
  }
  if (playerSelection === "Paper") {
    if (computerSelection === "Scissors") {
      console.log("You win");
    } else {
      console.log("You lose")
    }
  }
  if (playerSelection === "Scissors") {
    if (computerSelection === "Paper") {
      console.log("You win")
    } else {
      console.log("You lose")
    }
  }
}

RPS()

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

Display an image when the iframe viewport is reduced in size by utilizing media queries

I am looking to showcase a demo.html page within a 400px square iframe. When the viewport is smaller than 400px, I want demo.html to only display an image. Then, when clicking on that image in demo.html, the same page should switch to fullscreen mode. Sim ...

Google Chrome successfully transmits two variables with AJAX, whereas Mozilla Firefox does not send them

Having an issue with sending two values through ajax - currently only one value is being sent in Mozilla browser. Ajax script: $('#post_submit').click(function() { event.preventDefault(); var great_id = $("#post_container_supreme:first").attr(" ...

Expand Bootstrap accordion on hover

I have tried several examples that I discovered on Google and Stack Overflow, but none of them seem to work. So, I decided to attempt a different solution for opening the Bootstrap accordion on hover, however, it is not working as expected. Do you have any ...

Using localized strings in Spring and jQuery validation: Best practices

Consider this form as an illustration: <form id="login_form" method="post" action="/rest/auth/auth"> <div id="login_email" class="row margin-top-50"> <div class="col-md-12" id="input_container"> <input id="log ...

Using AJAX to send data to the server in jQuery

Currently, I have an AJAX request implemented on my webpage. I am exploring methods to detect when an AJAX call is initiated within the page using jQuery or JavaScript. Is there a way to identify or trigger a function upon the initiation of an AJAX reques ...

What is the best way to fulfill promises sequentially?

I'm currently facing a challenge with organizing promises in the correct order. I am developing a chat bot for DiscordApp using Node.js and have extensively searched both on this platform and Google. Despite trying Promise.all and an Async function, I ...

Persist a SQL entity to a document with the help of Node.js

I am looking for a way to store the data from the rows object either in a file or as a JSON file. app.get('/getposts', (req, res) => { mysqlConnection.query('Select * from posts', (err, rows, fields) => { if (!err) console.l ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

Creating a dual-column checkbox design with CSS only

I'm working with a dynamically generated form element that can only be styled using CSS. I need help achieving a specific layout without making any HTML changes, except for the classes. The "element" and "formField" classes are common and cannot be mo ...

Why Bootstrap 4 collapse feature is not functioning correctly within a ReactJS map component?

I am currently working on a project that requires implementing a collapse feature. The idea is to display all available content when the user clicks the Read More button (which is functioning as intended for collapsing). However, I am facing an issue where ...

Creating a WebSocket service similar to stackoverflow using Node.js: A step-by-step guide

I'm currently developing a chat application using node.js. I have implemented a feature to receive new messages via ajax, where requests are sent every 3 seconds. However, I recently observed that stackoverflow handles fetching new data differently. I ...

Guide to Implementing i18n-iso-countries Library in React

I am currently developing a React application and attempting to utilize the i18n-iso-countries package to retrieve a countries object in English where keys represent iso codes and values represent country names. This process is straightforward in Node.js, ...

A cookie designed to store and retain the preferred CSS stylesheet choice

I'm looking to create a cookie that will store the preference for a specific CSS stylesheet. I currently have a function in place that allows me to switch between stylesheets: function swapStylesheet(sheet){ document.getElementById('pagestyl ...

showcasing a map on an HTML webpage

Seeking advice on integrating a map feature in HTML to mark store locations. Working on an app for a business community and need help with this specific functionality. Your assistance would be greatly appreciated! ...

Tips for customizing the checked color of Material UI Radio buttons

If I want my radio button to be green instead of the default options (default, primary, secondary), how can I achieve that? I attempted to override the color using the classes prop like this: const styles = theme => ({ radio: { colorPrimary: { ...

Do form validations affect the values assigned to ng-model objects?

If a form has the structure below: <form> <input type="text" required ng-model='myValue' ng-maxlength='5'></input> {{myValue}} {{myValue.length}} </form> Is there a way to prevent the model from b ...

There was an issue with locating the module: Error: Unable to find the specified module 'vue-axios' in the directory 'C:xampphtdocsvue-laravel-api esourcesjs'

I am currently working on a CRUD project using Laravel and Vue.js. I made sure to install all the necessary devDependencies, but when I try running NPM run watch, I encounter the following error: My app.js file includes all the required dependencies: ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Encountering a problem with controlling the number of splits allowed

I am encountering an issue with splitting my string using the code below. splitter.map((item1) => { let splitter1 = item1.split("=")[0].trimLeft(); let splitter2 = item1.split("=")[1].trimRight(); }); The content of item1 is as fo ...

I am having trouble with my quiz function as it only checks the answer correctly for the first question. Does anyone have suggestions on how to make it work for

Currently, I'm tackling a quiz project that was assigned to me during my bootcamp. My focus right now is on the checkAnswer function, which evaluates the answer selected by the player. const startButton = document.querySelector(".start") as ...