javascriptincrementproduct-quantity

How to Decrement an Incremented counter as long as it stays zero or above and returns 0 instead of "undefined"?


incrementing and decrementing works as expected but I need the number to display '0' instead of 'undefined' if it becomes zero or less.

Currently, When it becomes zero, it goes one step more and returns undefined.
I need it to stay zero when it gets to zero.

let counter = 0;

const add = (function() {
  return function() {
    counter += 1;
    return counter;
  }
})();
const sub = (function() {
  return function() {
    if (counter >= 1) {
      counter -= 1;
      return counter;
    }
  }

})();

function addFunction() {
  document.getElementById("demo").innerHTML = add();
}

function subFunction() {
  document.getElementById("demo").innerHTML = sub();
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.buttons {
  background: crimson;
  margin: 10px;
  width: 130px;
  color: white;
  text-align: center;
  padding: 4px;
  display: flex;
  justify-content: space-around;
  border-radius: 5px;
}

button {
  width: 45px;
  height: 20px;
  margin: 5px;
}

p {
  margin: 5px;
}
<!DOCTYPE html>
<html>

<body>

  <div class="buttons">
    <button type="button" onclick="addFunction()">+</button>
    <button type="button" onclick="subFunction()">-</button>
    <p id="demo">0</p>
  </div>


</body>

</html>


Solution

  • You don't return anything when your condition fails. Just return your counter behind your if, so it will always return something.

    <!DOCTYPE html>
    <html>
    
    <style>
    
    *{margin:0; padding:0; box-sizing:border-box;}
    
    .buttons{ background: crimson; margin:10px; width: 130px; color: white; text-align: center; padding: 4px; display: flex; justify-content: space-around; border-radius: 5px;}
    
    button{width: 45px; height: 20px; margin: 5px;}
    
    p{margin: 5px;}
    
    
    </style>
    
    <body>
    
    <div class="buttons">
    <button type="button" onclick="addFunction()">+</button>
    <button type="button" onclick="subFunction()">-</button>
    <p id="demo">0</p>
    </div>
    
    <!--Script-->
    <script>
    let counter = 0;
    
    const add = (function () {
      return function () {counter += 1; return counter;}
    })();
    const sub = (function () {
      return function () {
      if(counter >= 1) {counter -= 1; return counter;}
      return counter
      }
    
    
     
    })();
    
    function addFunction(){
      document.getElementById("demo").innerHTML = add();
    }
    function subFunction(){
      document.getElementById("demo").innerHTML = sub();
    }
    
    </script>
    
    </body>
    </html>