:::: MENU ::::

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.



  • 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.

  • 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.

  • Final program in more readable code


So, what do you think ?