[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/accumulator [Back]  [Original]

Create new Accumulator
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Create new Accumulator

    importance: 5

    Create a constructor function Accumulator(startingValue).

    Object that it creates should:

    • Store the current value in the property value. The starting value is set to the argument of the constructor startingValue.
    • The read() method should use prompt to read a new number and add it to value.

    In other words, the value property is the sum of all user-entered values with the initial value startingValue.

    Heres the demo of the code:

    let accumulator = new Accumulator(1); // initial value 1
    
    accumulator.read(); // adds the user-entered value
    accumulator.read(); // adds the user-entered value
    
    alert(accumulator.value); // shows the sum of these values

    Run the demo

    Open a sandbox with tests.

    solution
    function Accumulator(startingValue) {
      this.value = startingValue;
    
      this.read = function() {
        this.value += +prompt('How much to add?', 0);
      };
    
    }
    
    let accumulator = new Accumulator(1);
    accumulator.read();
    accumulator.read();
    alert(accumulator.value);

    Open the solution with tests in a sandbox.


    Web Proxy Viewer  |  New URL  |  Original Page