Asanchez-2
Asanchez-2

Reputation: 75

Increasing,decreasing and total JavaScript

I have a beginner predeterminate exercise in React js, but I don´t know how to do it without a "state" when I try set the counter.

Can anyone help me?

class Counter {
  constructor() {
    //initialization of the counter variable
    this.counter = 0;
  }
  increaseOne() {
    //increase the value in one
  }
  decreaseOne() {
    //decrease the value in one
  }
  getValue() {
    //return the value
  }
}

let myNewCounter = new Counter();
myNewCounter.increaseOne();
console.log(myNewCounter.getValue());
myNewCounter.increaseOne();
myNewCounter.increaseOne();
console.log(myNewCounter.getValue());
myNewCounter.decreaseOne();
myNewCounter.decreaseOne();
console.log(myNewCounter.getValue());

My exercise have to show the following:

enter image description here

Upvotes: 0

Views: 119

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

In vanilla JS you don't have any states built-in. You just change the value of a property.

With the ++ and -- operators you can add or subtract with a value of 1. So in the increaseOne and decreaseOne methods change the value of the this.counter property.

class Counter {

  constructor() {
    this.counter = 0;
  }
  
  increaseOne() {
    this.counter++;
  }
  
  decreaseOne() {
    this.counter--;
  }
  
  get value() {
    return this.counter;
  }

}

let myNewCounter = new Counter();
myNewCounter.increaseOne();
console.log(myNewCounter.value);
myNewCounter.increaseOne();
myNewCounter.increaseOne();
console.log(myNewCounter.value);
myNewCounter.decreaseOne();
myNewCounter.decreaseOne();
console.log(myNewCounter.value);

For the getValue() method you can also use a getter method, which acts like a property but actually returns the result of a function. But this is just a suggestion and should make little difference.

Upvotes: 1

Related Questions