Computer >> Computer tutorials >  >> Programming >> Javascript

Function to reverse a string JavaScript


We are required to write a JavaScript function that takes in a string and returns a new string that is the reversed version of the original string.

The only condition is that we cannot use any inbuilt String methods and we cannot convert the string to array in order to reverse it.

We will have to use a loop to iterate over the string and construct a new reversed string.

Example

const str = 'Hello World';
const reverse = (str = '') => {
   const { length } = str;
   let res = '';
   for(let i = 0; i < length; i++){
      const el = str[i];
      res = el + res;
   };
   return res;
};
console.log(reverse(str))

Output

This will produce the following output −

dlroW olleH