[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/array-input-sum [Back]  [Original]

Sum input numbers
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

    Sum input numbers

    importance: 4

    Write the function sumInput() that:

    • Asks the user for values using prompt and stores the values in the array.
    • Finishes asking when the user enters a non-numeric value, an empty string, or presses Cancel.
    • Calculates and returns the sum of array items.

    P.S. A zero 0 is a valid number, please dont stop the input on zero.

    Run the demo

    solution

    Please note the subtle, but important detail of the solution. We dont convert value to number instantly after prompt, because after value = +value we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead.

    function sumInput() {
    
      let numbers = [];
    
      while (true) {
    
        let value = prompt("A number please?", 0);
    
        // should we cancel?
        if (value === "" || value === null || !isFinite(value)) break;
    
        numbers.push(+value);
      }
    
      let sum = 0;
      for (let number of numbers) {
        sum += number;
      }
      return sum;
    }
    
    alert( sumInput() );

    Web Proxy Viewer  |  New URL  |  Original Page