search

Home  >  Q&A  >  body text

JavaScript: increment and decrement functions

I'm practicing my JavaScript skills, I've been mastering a simple incrementing counter function that I seem to have mastered, so today I wanted to take that script to the next level and decrement the value,

Here is my problem, when I click add number and then continue clicking minus sign, the first click still adds a value before > The countdown is on, what am I missing to avoid this happening?

My code is as follows:

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>

P粉761718546P粉761718546349 days ago528

reply all(1)I'll reply

  • P粉759451255

    P粉7594512552024-01-30 00:21:19

    Use number When incrementing the number variable, this statement returns the value before the increment. If you want to get an incremented number, use number instead of number .

    For --, the same is naturally true.

    reply
    0
  • Cancelreply