I’m new to programming!
Trying to write a function that obtains the digital root of a number.
Currently struggling with the “for loop” and “if else” portion of the formula that returns “undefined”. Can you please give me any feedback and explain where my errors are specifically?
function digitalRoot(n) {
let sum = 0;// define variable for loop calculations
let str = n.toString(10,'')// convert number into string
if (str.length === 1) { // test if string length is more than 1 character
return str * 1; // if 1 character, return that string value and convert it back to a number
}
else {
return
let strArray = parseInt(str.split(','))// if more than 1 character, split string into individual characters & convert back to numbers
for (let i = 0; i < strArray.length; i++) { // sum up the numbers and repeat until there is just a single digit result
sum += strArray[i];
}
}
}