# 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
});```

## JavaScript job interview question – Find first non repeated character in string

There are several way to code this puzzle. Some of them are time intensive and some of them…

## JavaScript Error Fix – TypeError: document.getElementById(…).submit is not a function

Sometimes you try to validate HTML <form> using form validation javascript via some third party plugin or even…

## Javascript setTimeout() function jquery examples and chaining it with afterTime() plugin

javascript setTimeout() function It takes two arguments. Callback function to execute after milliseconds supplied. Milliseconds – after how…