Open In App

JavaScript Program for Sum of Digits of a Number using Recursion

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a number as input and we have to find the sum of all the digits contained by it. We will split the digits of the number and add them together using recursion in JavaScript.

Recursively Summing Digits

In this approach, we define a recursive function that takes an integer N as input and returns the sum of its digits. The base case occurs when the number is less than 10, in that case, the function simply returns the number itself.

Example: The below code sums the digits of a number using recursion in JavaScript.

Javascript
function sumOfDigits(n) {
    if (n < 10) {
        return n;
    }
    let quo = Math.floor(n / 10);
    return n % 10 + sumOfDigits(quo);
}

console.log(sumOfDigits(123));
console.log(sumOfDigits(249));
console.log(sumOfDigits(123456789));

Output
6
15
45

Using string manipulation with recursion

In this approach, we convert the number to a string usin toString() method, split it into individual digits using split() method, and then recursively sum them up.

Example: The below code sums up the digits of a number using string manipulation in JavaScript.

Javascript
function sumOfDigits(number) {
    let digits = 
        number.toString().split('').
        map(Number);
    if (digits.length === 1) {
        return digits[0];
    } else {
        let newNum = Number(digits.slice(1).join(''));
        return digits[0] + sumOfDigits(newNum);
    }
}

console.log(sumOfDigits(123));
console.log(sumOfDigits(249));
console.log(sumOfDigits(123456789));

Output
6
15
45

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads