Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript prevent decrement past 0

Tags:

javascript

Probably a rookie question, but how do I prevent the decrement from going past zero into the negative numbers?

public counter : number = 0;
increment(){
  this.counter += 1;
}

decrement(){
  this.counter -= 1;
}
like image 540
pjleinen Avatar asked Jul 13 '26 15:07

pjleinen


2 Answers

For clarity, I suggest to use the Math.max() function to make sure that the value is always greater than or equal to 0.

decrement(){
  this.counter = Math.max(0, this.counter - 1);
}

This is not the fastest way to do this but as long as you don't call decrement() in a loop for several hundred thousand times, the performance degradation is too small to be perceived.

like image 157
axiac Avatar answered Jul 15 '26 05:07

axiac


You simply check if the counter is still greater than zero and only if so you actually decrement your counter

decrement(){
  if(this.counter > 0){
    this.counter -= 1
  }
}
like image 39
Max K Avatar answered Jul 15 '26 05:07

Max K