Reversing a string in JavaScript solution #3
Thought we were done? Think again! In my previous blogs I’ve written two different ways to solve the infamous interview question. Today I’ll be providing you with a third way, and possibly the hardest one out of all three, but most impressive. We’re going to introduce a method called “.reduce()”. Let’s get started. As always, you want to start out by writing out your function declaration, and giving it the parameter of “str”.
Once we’ve finished that, we then want to turn our string into an array. Remember as I stated before by using the .split(“”) method? We’ll want to use it again. After converting our string we want to now use our helper method, which will be .reduce(). If you’re not familiar with .reduce, it’s basically used to take all the different values within an array and condense it down into one value. Reduce also takes two separate arguments, the first one will be an arrow function, and the second argument will be the starting initial value for the function, which will be an empty string. So far our code should look like this:
Whenever reduce runs, it takes the starting argument, passes it into the arrow function as the first argument, and whatever gets returned from the inner function, it will be used as the starting argument as every successful run of the function. Our first argument that is passed into our reduce method, will be our “reversed” string, and then our second argument, will be the element/character that we’re currently on in our array. Now if you remember to our for loop logic, where we added each character to the end of our string, we can apply that logic here, and make sure to return that result. Finally we should return the entire thing, so we can get our reversed string. At the end, our code should look similar to this.
I hope you enjoyed this blog, and I hope that this will help you out in future interviews, and understanding JavaScript more!