I’ve been learning javascript in school for a few months now and I’m trying to work a problem out on my own but I can’t seem to figure out what the issue is. The assignment is to "Create a for loop that starts at zero and loops once for each character in the number using the .length property." So for example, if I were to put in 2514 it should return 12.
Here is the piece I’m struggling with
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
} else {
numberPassed = parseInt(numberPassed)
let digitSum = 0;
for (let i = 0; i < numberPassed.length; i++) {
digitSum = numberPassed[i] + digitSum;
}
return digitSum;
}
}
When I test it in the browser it keeps giving me 0. If anyone could point me in the right direction I would greatly appreciate it.
>Solution :
parseInt() would convert numberPassed into a number. Thus, you wont be able to perform .length method to it.
You’d have to convert it into a string through, numberPassed.toString() and then while you are performing your addition, convert each digit back to INT through parseInt(numberPassed[i]) to get your desired result.
The code would look something like this,
function sumOfDigits(numberPassed) {
if (!isNaturalNumber(numberPassed)) {
return 'bad data';
} else {
numberPassed = numberPassed.toString()
let digitSum = 0;
for (let i = 0; i < numberPassed.length; i++) {
digitSum = parseInt(numberPassed[i]) + digitSum;
}
return digitSum;
}
}