How to reverse a string in JavaScript using a for loop & recursion

How to reverse a string in JavaScript using a for loop & recursion

There are many reasons why you might want to reverse a string in your code. Here are a few examples:

  • You may want to reverse a string to check if it is a palindrome, which is a word or phrase that is spelled the same way forwards and backwards (e.g. "racecar").
  • You may want to reverse the order of words in a sentence, or reverse the order of characters within a word.
  • You may want to reverse a string to create a new string that has a specific meaning when read backwards (e.g. "sdrawkcab" for "backwards").
  • You may want to reverse a string as part of a larger algorithm or data processing task.

There are three methods for reversing a string in JavaScript:

Using the split(), reverse(), and join() methods:

function reverseString(str) {
  return str.split('').reverse().join('');
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

Using a for loop:

function reverseString(str) {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

Using the reduce() method:

function reverseString(str) {
  return str.split('').reduce((reversed, char) => char + reversed, '');
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

Let's get to more details.

To reverse a string in JavaScript using a for loop, you can follow these steps:

Declare a variable reversed and initialize it to an empty string. This variable will be used to store the reversed string.

Set up a for loop to iterate over the characters in the string. The loop should start at the last character in the string and end at the first character. You can use the length property of the string to get the number of characters and the charAt() method to get the character at a specific index.

Inside the loop, add the character at the current index to the reversed variable. After the loop, return the reversed variable.

Here's the code that puts these steps together:

function reverseString(str) {
  let reversed = ''; // step 1
  for (let i = str.length - 1; i >= 0; i--) { // step 2
    reversed += str.charAt(i); // step 3
  }
  return reversed; // step 4
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

Let's go through an example to see how this code works. Suppose we have the string 'hello' and we want to reverse it. The loop will start with the index i set to the last character in the string, which is 'o'. The reversed variable is currently empty, so the first character to be added will be 'o'. The loop continues and i is decremented by 1. The next iteration of the loop starts with i set to 4, which is the index of the 'l' character. The reversed variable now contains 'o', so the next character added will be 'l'. This process continues until the loop ends and the reversed variable contains the reversed string 'olleh'.

Here's a more detailed explanation of the code:

The first step is to declare a variable reversed and initialize it to an empty string. This variable will be used to store the reversed string as it is built up character by character.

Next, we set up a for loop to iterate over the characters in the string. The loop starts at the last character in the string, which is str.length - 1. This is the index of the last character in the string, since JavaScript uses zero-based indexing (meaning the first character has an index of 0, the second character has an index of 1, and so on).

The loop continues until i is greater than or equal to 0. This means the loop will iterate over all the characters in the string, starting from the last character and ending at the first character.

Inside the loop, we use the charAt() method to get the character at the current index i. We then add this character to the reversed variable using the += operator. This operator adds the character to the end of the reversed string.

After the loop ends, we return the reversed variable, which now contains the reversed string.

How to reverse a string using recursion

To reverse a string in JavaScript using recursion, you can follow these steps:

Check if the string is empty or has only one character. If so, return the string. This is the base case of the recursion. If the string has more than one character, return the last character of the string concatenated with the result of calling the function with the string without its last character. Here's the code that puts these steps together:

function reverseString(str) {
  if (str.length <= 1) { // step 1
    return str;
  }
  return str.charAt(str.length - 1) + reverseString(str.slice(0, -1)); // step 2
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

Let's go through an example to see how this code works. Suppose we have the string 'hello' and we want to reverse it. The function is called with the argument 'hello', so the if statement in step 1 is false and the function continues to step 2. In step 2, the last character of the string, 'o', is concatenated with the result of calling the function with the string 'hell' (which is the original string without its last character).

This process continues until the function is called with a string that has only one character. At this point, the if statement in step 1 is true and the function returns the string, which ends the recursion.

The returned strings are concatenated as the recursion unwinds, resulting in the reversed string 'olleh'.

How to reverse a string in JavaScript without using any inbuilt functions

To reverse a string in JavaScript without using any inbuilt functions, you can use a for loop to iterate over the characters in the string and build up the reversed string character by character.

Here's an example:

function reverseString(str) {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

This code works by starting a loop at the last character in the string and iterating backwards to the first character. On each iteration, the character at the current index is added to the reversed variable. After the loop ends, the reversed variable contains the reversed string.

How to reverse a string in JavaScript using inbuilt functions

To reverse a string in JavaScript using inbuilt functions, you can use the split(), reverse(), and join() methods. Here's an example:

function reverseString(str) {
  return str.split('').reverse().join('');
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

The split() method is used to split the string into an array of characters. The reverse() method is used to reverse the order of the elements in the array. Finally, the join() method is used to join the elements of the array back into a string.

You can also use the reduce() method to reverse a string. Here's an example:

function reverseString(str) {
  return str.split('').reduce((reversed, char) => char + reversed, '');
}

let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'

The reduce() method applies a function to each element of the array, resulting in a single value. In this case, the function concatenates the current character with the reversed string (which starts as an empty string and grows on each iteration).