Codementor Events

Reverse a String Algorithm in Javascript

Published Jan 13, 2020Last updated Jan 15, 2020
Reverse a String Algorithm in Javascript

I recently stumbled on Steven Grinders Algorithms tutorial on Udemy. I perceive that the best way to learn is to get my hands dirty with a lot of practice so I committed to writing an article for every algorithm practiced with different methods of doing this.

Today I would be writing on Reversed String Algorithm, sharing different solutions to solving this issue below.

Using the .Reverse() Inbuilt Javascript Function.
Javascript has an in-built “reverse()” function which could be used to solve for this as demonstrated below. This approach splits the string, returning an array of strings separated by quotes. for example.

const randomString = "test";
const returnedString = randomString.split("");
console.log("response --->", returnedString);
// response ---> ["t","s","e","t"]

see full code snippet below.

 function reverse(str) {
   let reversedString = str.split("").reverse().join("")
   return reversedString
 };
 reverse('abcd');
// result --> dcba

Using the For Loop. (BruteForce Approach).

This approach uses the for-loop to iterate and in the process creates a new reversed string.

 function reverse(str) {
   let reversed = '';
   for (let character of str) {
     reversed = character + reversed;
   }
   return reversed;
 }

Using the Javascript “.reduce()” function.

The reduce function also does some looping under the hood which allows us to iterate through an array We would need to split the string to an array using the .split(“ ”) method. The result of this is an inverse string.

function reverse(str) {
return str.split('').reduce((a, b) => {
return b + a
  })
}
reverse('ade')
// result --> 'eda'

Using the Javascript Spread and .Reverse().

Using the spread operator on a string returns a split string in an array. for example.

const testArray = "ade";
const newSpreadString = [...testArray];
console.log(newSpreadString);
// result ["a", "d", "e"]

now that we have an array of strings returned, we can go further to use the > ".Reverse()" method as seen below.

function reverse(str){
  return [...str].reverse().join('');
}
reverse('abc');
// result 'cba'
Discover and read more posts from Sunny Edogbo
get started