JavaScript Reverse Method

Adam James
3 min readSep 4, 2021

--

Throughout learning more about JavaScript and coding there has been one JavaScript method that I haven’t really been able to grasp completely, the reduce method. Reduce takes every element in an array and returns a reduced, single value. In Mozilla’s web documentation, reduce() takes in an array, executes a callback function on each element, and returns the final value as a single value once the function has ran through every element of the array. In this post, I’ll take some time to explain some basics of the method, along with using the method in a basic function that can be used to reverse a string.

The web documentation says that the best way to describe how reduce() works is to sum all of the values of an array. If you pass a callback function or an arrow function into reduce() that tells the method to add the current element to the summed total, it will return a single integer that’s the sum of the values.

Going further into how the function works, the method can accept a second argument that’s the initial value of the function. For example, if the method above had an initial value of 1, the returned value would be 11. If the method had an initial value of 15, the returned value would be 25.

Say you want to write a function that reverses a passed-in string. It’s a pretty simple concept with multiple ways to write out a solution. The most obvious logic behind the function, in my opinion, would be to create a variable set to an empty string, then iterate through the initial string to place the current character at the front of the string. This would require multiple lines to complete the problem, but by using reduce() you could have a creative solution in a single line.

Since reduce() needs to be used on an array, the first move for this function is to split the string into an array. After that method, the reduce method is able to be chained onto the end. For the arrow function, I want to look at the full reversed string, rev, which starts as an empty string in the initial value slot of the method. As this method runs, each character, char, is isolated and appended onto the front of the rev string.

For example, if the passed-in string is ‘abcd’, the reduce method would start with the initial value of “” as the rev value in the callback function, and the char value would be ‘a’, at the second loop, rev would be ‘a’, and the current character would be ‘b’, which after appending, the rev string would be ‘ba’. After the function finishes running, the array will be reduced into a single value of ‘dcba’.

--

--

No responses yet