Although one answer has already been marked as correct, I'd like to offer my own perspective. The answers provided above may work in certain cases, but they are prone to bugs due to the unreliable nature of user input.
@Luis's answer is effective, but have you considered inputting alphanumeric characters like 1bs64s
? When parsed, it returns just the number 1. This unexpected behavior could be confusing for users, even though it might be acceptable to you. It's crucial to consider the user's perspective when allowing alphanumeric inputs.
Here is an explanation of why this issue occurs if you're curious:
When parseInt encounters a non-numeric character in the specified radix, it disregards that character and all following ones, returning the integer value parsed up to that point. Leading and trailing spaces are permitted, and numbers are truncated to integers.
Simply setting the radix base to 10 doesn't fully resolve the problem, as demonstrated by @Programmer's scenario with numbers between 0 and 100 still being accepted.
@Pbd's answer also experiences similar issues, coercing strings into numbers without proper validation.
// Without proper validation, this condition allows `1e1` to be stored in an array.
if("1e1" <= 100 && "1e1" >= 0) // evaluates to true!
Due to dynamic typing, the output differs upon summation.
var sum = 0;
sum += totalInputs[i] // assuming totalInputs[i] returns `1e1`
console.log(sum); // outputs "01e1".
There are various strategies for validating inputs securely, but in my opinion, trimming user input, converting strings to numbers, and validating convertibility into integers is a reliable approach.
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; // checking equality "1" == 1
if(userInput && isNumber && convertedInput >= 0 && convertedInput <= 100)
totalInputs[j] = convertedInput;
To simplify the summation process, consider using reduce.
var sum = totalInputs.reduce(function(pv, cv) { return pv + cv; }, 0);
Alternatively, with arrow functions from ES6, the code becomes even more concise:
var sum = totalInputs.reduce((pv, cv) => pv+cv, 0);
Credit goes to @Chaos's answer. I haven't tested reduce performance across different browsers yet.
Javascript can be quite enjoyable! :)