Nic Meiring - 1 year ago 87

Javascript Question

I saw a bunch of other posts on this topic but none in javascript. here is my code.

`var theNumber = function digitAdd (base, exponent) {`

var number = 1;

for (i=0; i < exponent; i++) {

var number = base * number;

}

return number

}

function find(theNumber) {

var sum=0;

parseInt(theNumber);

while(theNumber>0)

{

sum=sum+theNumber%10;

theNumber=Math.floor(theNumber/10);

}

document.writeln("Sum of digits "+sum);

}

find(theNumber (2, 50));

I am getting the correct answer, I just don't fully understand the 2nd function, namely the while statement. Any help would be greatly appreciated. Thanks!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The second function uses the modulo operator to extract the last digit:

```
1236 % 10
= 1236 - 10 * floor(1236 / 10)
= 1236 - 1230
= 6
```

When the last digit is extracted, it is subtracted from the number:

```
1236 - 6
= 1230
```

And the number is divided by `10`

:

```
1230 / 10
= 123
```

Each time this loop repeats, the last digit is chopped off and added to the sum.

The modulo operator returns `0`

if the left hand side is smaller than the right (which will happen for any 1-digit number), which is when the loop breaks:

```
1 % 10
= 0 (no whole-number multiples of 10 go into 1)
```

A less numeric alternative would be this:

```
function sumDigits(number) {
var str = number.toString();
var sum = 0;
for (var i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 10);
}
return sum;
}
```

It does literally what you are trying to do, which is iterate over the digits of the number (by converting it to a string).

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**