0

I'm trying to create a little Javascript program that adds 1 when I click a "+" button, and subtracts 1 when I click a "-" button. It works, however when I add 1 then goto subtract one, the first click of the "-" button will add one more, before subtracting.

Eg. 1, 2, 3, 4, (then I click the "-" button) 5, 4, 3...

   var number = 1;
<button type="button" onClick="document.getElementById('number').innerHTML = number++">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = number--">-</button>
<div id="number"></div>


 
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • 2
    `number++` returns the number, THEN increments it. `++number` increments the number THEN returns it. – random_user_name Feb 01 '19 at 14:55
  • `number++` is being used as the post-increment operator. It returns the current value of the variable and _then_ increments the variable. You should be using the pre-increment version `++number` – phuzi Feb 01 '19 at 14:55

2 Answers2

3

that is basically because you are doing number++ and you should do ++number.

var number = 0;
<button type="button" onClick="document.getElementById('number').innerHTML = ++number">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = --number">-</button>
<div id="number"></div>

to understand what happens you need to know the following;

a++ will return a and then do the ++ operation.

++a will return the result of doing the ++ operation over a.

var a = 5;
var b = 8;

console.log(a++) // will show 5.
console.log(a) // will show 6, because the ++ operation was executed.

console.log(++b) //will show 9. because the ++ operation was executed.
console.log(b) // will keep showing 9.
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
0

++number will increment the value of number, and then return the incremented value.

var number=1;
<button type="button" onClick="document.getElementById('number').innerHTML = ++number">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = --number">-</button>
<div id="number"></div>

number++ will increment the value of number, but return the original value that i held before being incremented.

var number =1;
<button type="button" onClick="document.getElementById('number').innerHTML = number++">+</button>
<button type="button" onClick="document.getElementById('number').innerHTML = number--">-</button>
<div id="number"></div>
ellipsis
  • 12,049
  • 2
  • 17
  • 33