Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
How do you display a counter variable inside a div?

Im building rock/paper/scissors where user plays against computer. I want to update the score after each round and display it inside a div. The code works after the 1st score, but never increments after 1.

let computerPlay = () => {
  let compChoices = ["rock", "paper", "scissors"]; //array storing computer possible actions
  let i = Math.floor(Math.random() * 3);
  let choice = compChoices[i];

  return choice;
};

//select buttons for player choice
let buttons = document.querySelectorAll(".btn");

//select elements for updating scoreboard
let homeScore = document.querySelector(".home-score");
let awayScore = document.querySelector(".away-score");
let display = document.querySelector(".score-board-display");

//declare player and computer score variables
let playerScore, compScore;

//compare player and computer selections update score of winner
let playRound = (playerSelection, computerSelection) => {
  let result = ``;
  playerScore = 0;
  compScore = 0;
  if (playerSelection === computerSelection) {
    result = `Tie ${playerSelection} equals ${computerSelection}`;
  } else if (
    (playerSelection == "rock" && computerSelection == "scissors") ||
    (playerSelection == "paper" && computerSelection == "rock") ||
    (playerSelection == "scissors" && computerSelection == "paper")
  ) {
    result = `LFG!! ${playerSelection} beats ${computerSelection}`;
    playerScore += 1;
    homeScore.innerText = playerScore.toLocaleString();
  } else {
    result = `You Lose! ${computerSelection} beats ${playerSelection}`;
  }

  return (display.innerHTML = result);
};

buttons.forEach((button) => {
  button.addEventListener("click", () => {
    let computerSelection = computerPlay();
    let playerSelection = button.innerHTML.toLowerCase();
    playRound(playerSelection, computerSelection);
  });
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

on every playRound the playerScore is reseted / defined as 0

to solve that define playerScore as number before your playRound definition

...
let playerScore=0;
let playRound = (playerSelection, computerSelection) => {
   ...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!