Single Line Statements in JavaScript: Reverse a String

In this series, our objective is to implement solutions that helps us understand and become a better developer using as less code as possible while still trying to maintain the readability. Less code leads to lesser bugs and when done right, leads to better performance.

To achieve that, we will be using the magical powers of ES6 and this series assumes you are familiar with it. If not, I strongly recommend you to learn as and when you encounter anything that is ES6. This is the first post in the series.


Reversing a string is a simple concept. But unlike other languages, JavaScript does not provide a built-in method to perform this action. For example, PHP offers strrev(). However, JavaScript can reverse an array. So you see where we are heading!

Let’s take a string for example:

const originalString = “coffee”

Reversed String:

“eeffoc”

Alright, let’s get into it:

  1. split() the string of letters and store them in an array.
  2. Reverse the array using array.prototype.reverse()
  3. Join all the letters to form a new string using join()

While this serves the purpose, we developers love modularity and reusability. That’s when Functions come into the picture.

Let’s create a Function, that accepts a String as an argument, reverses it and returns the value using the code we wrote above.

The above Function can now be reused every time we are in need of reversing a string, but that’s still a lot of code.

What we could do here is completely eliminate the need of declaring variables and storing the values after each operation such as split() and reverse() by chaining them all together to perform the same in a sequence.

With ES6 Arrow Functions:

  • When there’s just one parameter being passed, there’s no need to wrap it with parenthesis.
  • Skip the “return” keyword as it can implicitly return the value.
  • Remove the curly braces around execution body.

Looks clever and way simpler, isn’t it?



Feel free to write a feedback, comment and share it with your friends.

You can find me on Twitter and Github