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.
Let’s take a string for example:
const originalString = “coffee”
Alright, let’s get into it:
- split() the string of letters and store them in an array.
- Reverse the array using array.prototype.reverse()
- 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?