Although you already mark one as an answer but I'll try to throw my own version. Both answers above will only work in some cases. It's prune to bug why? Because you can't trust user's input.
@Luis's answer is good, but have you tried inputting alphanumeric like 1bs64s
? You'll find that after parsing it return number 1. Your user didn't expect that probably but if that's okay with you I think "I'll stop here" but in user's perspective it might be weird because you allow to add alphanumeric.
Below are the description why it happen if you are curios.
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point. parseInt truncates
numbers to integer values. Leading and trailing spaces are allowed.
Well, after you read that you'll probably say, that's easy lets just put the radix
base of 10 to solve the problem. No, it didn't. Since the program accept a range of number from 0-100 @Programmer's program will still accept it.
@Pbd's answer has issue too and suffer same faith described above. He just simply coercing string to number without proper validation.
// this condition without properly validation returns true. Allowing `1e1` to store in array.
if("1e1" <= 100 && "1e1" >= 0) // is true!
upon summing up the output is different(dynamic typing).
var sum = 0;
sum += totalInputs[i] // assuming totalInputs[i] returns `1e1`
console.log(sum); // the output is "01e1".
There are probably many versions for validation to keep you safe but IMHO is to trim user's input, coerces string to number and validate if input is convertible into integer.
userInput = window.prompt("Enter a test score, or 999 to end the program").trim(); // or userInput = userInput.trim();
var convertedInput = +userInput;
var isNumber = convertedInput == userInput; // check equality "1" == 1
if(userInput && isNumber && convertedInput >= 0 && convertedInput <= 100)
totalInputs[j] = convertedInput;
In addition to simplify summation use reduce.
var sum = totalInputs.reduce(function(pv, cv) { return pv + cv; }, 0);
or with arrow functions introduced in ES6, it's even simpler:
var sum = totalInputs.reduce((pv, cv) => pv+cv, 0);
Credit goes to @Chaos's answer. I haven't check reduce cross browser perf.
Javascript is fun! :)