skip to Main Content

I have made a project that is a simple counter with three buttons “decrease”, “reset” and “increase”

Each have onclick events attached to them.

Here is my code for my html file and each function respectively in my js file.

<body>
  <wrapper>
    <h1>Counter</h1>
    <h2 id="counter">0</h2>
     <div class="buttonContainer">
        <button onclick="decrease()">Decrease</button>
        <button onclick="reset()">Reset</button>
        <button onclick="increase()">Increase</button>
     </div>
 </wrapper>
</body>
Let i = 0;

function increase() {
  document.getElementById(‘counter’).innerHTML = i;
i++;
}

function decrease() {
  document.getElementById(‘counter’).innerHTML = i;
i—-;
}

function reset() {

i = 0;
document.getElementById(‘counter’).innerHTML = i
}

I’ve been trying to figure why when I make my code in this order for increase() and decrease() functions it seems to for example….if counter is at 1 and I click increase, I have to click it twice before it increases but then when I click decrease, it will increase it by 1 and then decrease and vice versa as well?

But when I have the i++ or i– first before getting the id it seems to work fine? e.g.

Let i = 0;

function increase() {
i++;
  document.getElementById(‘counter’).innerHTML = i;

}

function decrease() {
i--;
  document.getElementById(‘counter’).innerHTML = i;
}

I’m not sure why it does this if anyone can help?

I’ve solved this in terms of getting the project to work the way I want but I can’t work out why the increase would decrease the counter before increasing and vice versa when my functions don’t reference each other in any way?

2

Answers


  1. Code is executed from the top to the bottom, not the other way around

    let i = 0;
    
    function increase() {
      i++;
      document.getElementById('counter').innerHTML = i;
    }
    
    function decrease() {
      i--;
      document.getElementById('counter').innerHTML = i;
    }
    
    function reset() {
      i = 0;
      document.getElementById('counter').innerHTML = i
    }
    <button onclick="decrease()">Decrease</button>
    <button onclick="reset()">Reset</button>
    <button onclick="increase()">Increase</button>
    <p id="counter">0</p>
    Login or Signup to reply.
  2. Numbers are "Value Types", which means if you assign them to a new variable or pass them into a function, the value will be copied. In contrast, on "Reference Types", the behaviour is just the pointer will be copied instead of the value.

    Value Type sample:

    let i = 4;
    let j = i;
    i++; // it only changes i
    

    Reference Type sample:

    let i = {value:4};
    let j = i;
    i.value++; // it also changes j
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search