Sum-mer

by Sam Fereday

JavaScript

function sumOfDigit(num)
{

		var sum = 0,
    remainder = 0,
    a = num,
    base = 10;
    
    // 'a' will be modified after the first loop, so i will always be less than it.
		for(var i = 0; i < a; i++) {
    	// We get the remainder of 'a' from base ten so get the individual value given by 'n'.
    	remainder = a % base;
      // As the number is split, we add it to the sum.
      sum += remainder;
      // Dividing 'a' by 10 (which is the number given), will change its value to the 'length' of the argument given.
      a = a / base;
    }
    
    return sum;

}

// Result should be 3
var result = sumOfDigit(12345);
console.log(result);