0

I'm trying to make a simple counter, where clicking on a button named "+" should increase a variable (Score) by 1 and button "-" should decrease it by 1. Thing is, whenever I press + the first time, Score actually goes down by one before increasing on the second click, and vice versa with "-". What am I doing wrong?

By the way, I'm just coding for fun and am also new at Stack Overflow, so excuse the messy code.

<!DOCTYPE html>
<html>

<p id="Score1">
    
</p>
    
<p id="Score2">
    
</p>

    
    <button type: button onclick= PlusOneTeam1()>
        +
    </button>
    
    <button type: button onclick="MinusOneTeam1()">
        -
    </button>
    
    <button type: button onclick="PlusOneTeam1">
        +
    </button>
    
    <button type: button onclick="MinusOneTeam2">
        -
    </button>

<script>
    
    var Score = 0
    
    document.getElementById("Score1").innerHTML = Score

function PlusOneTeam1() {
    document.getElementById("Score1").innerHTML = Score ++  ; 
    return Score ;
}

    
function MinusOneTeam1() {
    document.getElementById("Score1").innerHTML = Score -- ;
}
</script>
    
    
</html>
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • 2
    1) Fix the HTML 2) [See what `i++` and `i--` *really does* in JavaScript](https://codeburst.io/javascript-increment-and-decrement-8c223858d5ed) – user2864740 Sep 11 '18 at 00:28
  • 1
    Use `++` as prefix (pre-increment): `++Score`. Check [this related question](https://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript) – Ram Sep 11 '18 at 00:29
  • 1
    Thanks! Using it as a pre-increment worked. – Norman De Barath Holst Sep 11 '18 at 00:34

1 Answers1

2

You may need to use += 1 or ++a here.

From the documentation:

The increment operator increments (adds one to) its operand and returns a value.

If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

Let's look at some code

let a = 1
let b = a++

console.log(a, b) // a is 2, b is 1

This is because a++ returns a as is, here then after the expression is evaluated it adds one to a.

let a = 1
let b = ++a

console.log(a, b) // 2, 2

Both values are 2 here because ++a first increments a then returns the updated value of a placing it into the expression.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()

CodeDraken
  • 1,163
  • 6
  • 12