Sum all the digits of a number Javascript

With mathy formula:

function sumDigits(n) { 
    return (--n % 9) + 1;
}

Without mathy formula:

function sumDigits(n) {
    if (typeof n !== 'string') {
        n = n.toString();
    }    
    if (n.length < 2) {
        return parseInt(n);
    }
​
    return sumDigits(
        n.split('')
         .reduce((acc, num) => acc += parseInt(num), 0)
    );
}

Basically you have two methods to get the sum of all parts of an integer number.

  • With numerical operations

    Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.

var value = 2568,
    sum = 0;

while (value) {
    sum += value % 10;
    value = Math.floor(value / 10);
}

console.log(sum);
  • Use string operations

    Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.

var value = 2568,
    sum = value
        .toString()
        .split('')
        .map(Number)
        .reduce(function (a, b) {
            return a + b;
        }, 0);

console.log(sum);

For returning the value, you need to addres the value property.

rezultat.value = sum;
//      ^^^^^^

function sumDigits() {
    var value = document.getElementById("thenumber").value,
        sum = 0;

  while (value) {
      sum += value % 10;
      value = Math.floor(value / 10);
  }
  
  var rezultat = document.getElementById("result");
  rezultat.value = sum;
}
<input type="text" placeholder="number" id="thenumber"/><br/><br/>
<button onclick="sumDigits()">Calculate</button><br/><br/>
<input type="text" readonly="true" placeholder="the result" id="result"/>

How about this simple approach using modulo 9 arithmetic?

function sumDigits(n) {
  return (n - 1) % 9 + 1;
}