JS Exercise: Sum of a String

Photo by Jess Bailey on Unsplash

JS Exercise: Sum of a String

Feeling confident in Javascript?

Well, given a string of lowercase letters, would you be able to sum them all up into 1 value? In one line of code?

Solution and explanations are below.

The Solution

const lettersum = s => s .split('') .map(c => c.charCodeAt(0) - 96) .reduce((a, b) => a + b, 0);

Pretty concise, isn't it? Let's go over this step-by-step

JS Arrow functions

'const lettersum = s =>'

First, we use 'const' to declare a variable (named 'lettersum') whose value shouldn't change later.

Then we begin to declare a function using a compact definition called an 'arrow function expression'.


s .split('')

This is the same as s.split() However, JS ignores newlines (line-terminators) when they separate bits of code (except in cases where it auto-inserts ';' like in return)

We do this so as we chain multiple functions, it stays easy to read

So what does 's.split('')' do?

Well, split() is a string method, that will divide the string into substrings, and returns them as an array.

In this case, '' means we want to divide the string at every character.

This gives us the string as an array of characters


 .map(c => c.charCodeAt(0) - 96)

Map accepts a function and will return the array created from calling the function on every element in the array.

Here we are going through our array of characters, and turning each one into a digit, subtracting 96 so a=0.


 .reduce((a, b) => a + b, 0);

Lastly, this reduces the list down to a single value.

It calls the function we pass on each item in the array, storing the result in 'a' and calling the function again with 'b' set as the next value in the array.

Here we are summing up every element in the list.


And that's it! So in summary, we

  • Split the string into characters
  • Go through each character, converting it into a number
  • Sum up all the numbers

Thanks for sticking around, and stay tuned for the next JS lesson.