pjleinen
pjleinen

Reputation: 79

Javascript prevent decrement past 0

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;
}

Upvotes: 5

Views: 10447

Answers (4)

Omar
Omar

Reputation: 51

you can do it using ternary operator too.

value > 0 ? value - 1 : 0

Upvotes: 0

axiac
axiac

Reputation: 72226

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.

Upvotes: 13

Max K
Max K

Reputation: 1121

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
  }
}

Upvotes: 3

tadman
tadman

Reputation: 211610

Write the function to clamp it at zero:

decrement(){
  this.counter -= 1;
  if (this.counter < 0) {
     this.counter = 0;
  end
}

Upvotes: 1

Related Questions