# JavaScript Quiz – write a one line program to calculate the sum of its digits

This code puzzle could be  asked to frontend engineer or even to experienced web designer.  Given input string of numbers, find the sum of all digits.

Answer could be tricky in programming languages like c or c++ if you have been asked to solve within a single line.

## Solution

`input.toString().split("").reduce(function (i, j, key, value) { ni = Number(i); nj = Number(j); return ni + nj });`

### Explanation

• Breaking this program logic into pieces.
• input.toString() It’ll convert input numbers into string.
• input.toString().split() It’ll convert converted number string into array.
• `input.toString().split().reduce(callback);`

javascript reduce function applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

i.e. each element from converted array will be passed to this function one by one. return value will be retained as first argument and new value will be second argument. in our case sum will be passed as first argument into reduce function and array element will be second one.

```reduce(function (return_value, array_element, key, value) {
rv = Number(return_value);
ae = Number(array_element);
return rv + ae;
});```
• Final program in more readable code
```input.toString()
.split("")
.reduce(function (i, j, key, value) {
ni = Number(i);
nj = Number(j);
return ni + nj
});```

## Tweet post or Facebook like to unlock the content using jQuery

##### Related Posts ## RequireJS example – loading desktop vs mobile javascript libraries and overriding functions

RequireJS is a JavaScript library that is used to load other JavaScript files in certain orders based upon…

## Front-End Engineer in San Francisco – solved code interview questions

I’ve came to this site (via hacker news) had few frontend engineer’s job interview questions. I’ve try to solved…

## How to manipulate cookie of array, object and json datatype using jQuery Plugins?

What’s Cookie A Cookie is a small amount of key value-based browser storage used to store tiny data…