0

I am practicing my JavaScript Skills, I have been mastering a simple increment counter function which I seem to have gotten right, so today I wanted to take that script to the next level and decrement the value too,

Here is my issue, when I click add number, then I proceed to click minus number, the first click still adds one value before it is counting down, what am I missing to avoid this from happening?

My code is below:

const output = document.getElementById('counter');
const addBtn = document.getElementById('btn-add');
const minusBtn = document.getElementById('btn-minus');
let number = 0;

function increment() {
  output.innerHTML = number++;
}

function decrement() {
  output.innerHTML = number--;
}

addBtn.addEventListener('click', increment);
minusBtn.addEventListener('click', decrement);
<div class="container">
  <h1>Increment and Decrement Numbers</h1>
  <div class="output">
    <div>
      <p>Your total count is: <span id="counter"></span></p>
    </div>
    <div class="buttons">
      <button id="btn-add">+</button>
      <button id="btn-minus">-</button>
    </div>
  </div>
</div>
David Thomas
  • 249,100
  • 51
  • 377
  • 410
TrevTheDev
  • 37
  • 1
  • 9
  • This is, because you are using a postincrement and postdecrement operator ... Use preincrement and decrement instead. – derpirscher Jan 03 '23 at 11:00
  • ```number++``` returns the value before the increment. – Koen Lostrie Jan 03 '23 at 11:01
  • From MDN: The increment (++) operator increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed. – T.Demirer Jan 03 '23 at 11:40

1 Answers1

0

when using number++ to increment the number variable, the statement returns the value before incrementation. You want to use ++number instead of number++ if you want to get the number after the incrementation.

Likewise for --, naturally.

Arthur Boucher
  • 307
  • 1
  • 7
  • 1
    _"when using ++ to increment a number, the statement returns the value before incrementation"_ - There are two version of the `++` operator, hence the sentence, in its current form, is only partially true. – Andreas Jan 03 '23 at 11:03
  • Thanks so much, I understand that now, i was watching some lectures about that last time but didnt make as much sense, after your advice and implementing your solution, i totally grasp it now thank you – TrevTheDev Jan 03 '23 at 11:37
  • @Andreas Absolutely true, edited for clarity. – Arthur Boucher Jan 04 '23 at 10:04