DEV Community

Cover image for Basic Exercises in JavaScript | Reverse a string (7 different ways)
{ PilaGonzalez }
{ PilaGonzalez }

Posted on

Basic Exercises in JavaScript | Reverse a string (7 different ways)

Solution #1

function reverseString(str) {
     return str.split('').reverse().join('');
}
Enter fullscreen mode Exit fullscreen mode

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. str.split(''): This line takes the input string str and uses the split('') method. The split method is used to split a string into an array of substrings. In this case, it splits the string into an array of individual characters. The argument '' is an empty string, which means it will split the string at every character, effectively converting the string into an array of characters. For example, if str is "hello," this line would produce the array ['h', 'e', 'l', 'l', 'o'].

  2. .reverse(): After splitting the string into an array of characters, the reverse() method is called on that array. This method reverses the order of elements in an array. So, if the array was ['h', 'e', 'l', 'l', 'o'], after calling reverse(), it becomes ['o', 'l', 'l', 'e', 'h'].

  3. .join(''): Finally, the join('') method is called on the reversed array. This method joins all the elements of the array back together into a single string, with no characters in between. In other words, it concatenates the characters of the array. So, in this case, it joins ['o', 'l', 'l', 'e', 'h'] into the string "olleh," which is the reversed version of the input string.

  4. The end result is that the reverseString function takes an input string, splits it into an array of characters, reverses the order of those characters, and then joins them back together to form the reversed string, which is then returned as the function's result.


Solution #2

function reverseString(str) {
     return [...str].reverse().join('');
}
Enter fullscreen mode Exit fullscreen mode

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. return [...str]: This part of the code uses the spread operator ([...]) to convert the input string str into an array of characters. This is done by splitting the string into individual characters and creating an array from them.

  2. .reverse(): After converting the string to an array of characters, the reverse() method is called on the array. This method reverses the order of elements in the array, effectively reversing the order of characters in the original string.

  3. .join(''): Finally, the join('') method is called on the reversed array to concatenate its elements back together into a single string. The empty string '' passed as an argument to join() specifies that there should be no separator between the characters, effectively merging them together.

  4. So, when you call reverseString with a string as an argument, it converts the string into an array, reverses the order of the elements in the array, and then joins them back together into a reversed string, which is returned as the result of the function.


Solution #3

function reverseString(str) {
     let reversed = '';
     for (let character of str) {
       reversed = character + reversed;
     }
     return reversed;
}
Enter fullscreen mode Exit fullscreen mode

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. let reversed = '';: This line initializes an empty string reversed. This variable will be used to store the reversed version of the input string.

  2. for (let character of str) { ... }: This is a for...of loop that iterates through each character in the input string str. It goes through the string one character at a time.

  3. reversed = character + reversed;: Inside the loop, the current character (a single character from str) is concatenated to the beginning of the reversed string. This effectively builds the reversed string in reverse order. For example, if the input string is "Hello," the loop will first add "o" to reversed, then "lo," and so on until the entire string is reversed.

  4. The loop continues until it has processed all characters in the input string.

  5. Finally, after the loop completes, the reversed string contains the reversed version of the input string, and return reversed; is used to return this reversed string as the result of the function.


Solution #4

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

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. let reversed = '';: This line initializes an empty string variable called reversed. This variable will be used to store the reversed string.

  2. for (let i = str.length - 1; i >= 0; i--) {: This line starts a for loop. It initializes a loop variable i to the length of the input string str minus one (since array indices in JavaScript are zero-based), and the loop continues as long as i is greater than or equal to 0. In each iteration, it decrements i by 1.

  3. reversed += str[i];: Inside the loop, this line appends the character at the current index i of the input string str to the reversed string. This effectively reverses the characters in the string because it starts from the end of the input string and works its way backward.

  4. The for loop continues until it has iterated through all the characters in the input string, effectively reversing the order of the characters.

  5. Finally, return reversed; is used to return the reversed string, which now contains the input string with its characters reversed.


Solution #5

function reverseString(str) {
     let reversed = '';
     str.split('').forEach(character => reversed = character + reversed);
     return reversed;
}
Enter fullscreen mode Exit fullscreen mode

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. let reversed = '';: This line initializes an empty string reversed, which will eventually hold the reversed version of the input string.

  2. str.split(''): This part of the code splits the input string str into an array of individual characters. The split('') method is used with an empty string as the separator, which effectively splits the string into an array of characters.

  3. forEach(character => reversed = character + reversed): This is a loop that iterates over each character in the array of characters obtained from the input string. For each character, it appends that character to the beginning of the reversed string. The character + reversed expression concatenates the current character with the existing reversed string. Since we are adding characters to the beginning of reversed, the characters are effectively reversed.
    For example, if the input string is "hello," the loop would go through each character and build the reversed string like this:
    Iteration 1: 'h' + '' => 'h'
    Iteration 2: 'e' + 'h' => 'eh'
    Iteration 3: 'l' + 'eh' => 'leh'
    Iteration 4: 'l' + 'leh' => 'lleh'
    Iteration 5: 'o' + 'lleh' => 'olleh'

  4. After the loop has finished processing all the characters in the input string, the reversed variable will contain the reversed string.

  5. Finally, return reversed; returns the reversed string as the result of the reverseString function.


Solution #6

function reverseString(str) {
     let reversed = "";
     str.split("").map((character) => (reversed = character + reversed));
     return reversed;
}
Enter fullscreen mode Exit fullscreen mode

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. let reversed = '';: This line initializes an empty string variable called reversed. This variable will be used to store the reversed string.

  2. str.split(''): This part of the code splits the input string str into an array of individual characters. It does so by calling the split('') method on the string with an empty string as the separator. This effectively separates each character in the string into an array element.

  3. .map(character => reversed = character + reversed): This part of the code uses the map function to iterate through each character in the array of characters created in the previous step. For each character, the code performs the following:

  4. character: This represents the current character in the iteration.

  5. reversed = character + reversed: This code concatenates the current character with the reversed string. It adds the current character to the beginning of the reversed string. This effectively reverses the order of characters since each character is added to the start of reversed.

  6. return reversed;: After the map function has processed all characters and reversed the string, the function returns the reversed string as the result.


Solution #7

function reverseString(str) {
    return str.split('').reduce((reversed, character) => character + reversed, '');
}
Enter fullscreen mode Exit fullscreen mode

Test

console.log(reverseString('hello')); // olleh
Enter fullscreen mode Exit fullscreen mode

Step by Step

  1. str.split(''): This line takes the input string str and uses the split method to split it into an array of individual characters. The argument '' is used as the separator, which means each character in the string will become a separate element in the resulting array. For example, if str is "hello," the result will be ['h', 'e', 'l', 'l', 'o'].

  2. .reduce((reversed, character) => character + reversed, ''): After splitting the string into an array of characters, the reduce method is called on the array. The reduce method is used to iterate through the array and accumulate a single value based on the elements in the array.

  3. (reversed, character) => character + reversed: This is an arrow function used as the callback function for reduce. It takes two parameters: reversed and character. reversed is the accumulating value, which starts as an empty string (''), and character is the current character being processed from the array.

  4. character + reversed: In each iteration of reduce, this expression concatenates the current character (character) with the accumulated reversed string (reversed). The character is added in front of the existing reversed string. This effectively builds the reversed version of the input string.

  5. The result of the reduce operation is the reversed string, which is returned by the reverseString function.

  6. So, when you call reverseString("hello"), it splits the string into an array of characters (['h', 'e', 'l', 'l', 'o']) and then uses reduce to reverse the order of these characters, resulting in the string "olleh".


Notes

  • The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
  • The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
  • The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
  • Notice that we don’t leave a space between the empty quote marks for .join(β€˜ β€˜). The space is necessary otherwise the string returned would have each character separated from the rest by a comma.
  • The spread operator is used to expand an iterable object into the list of arguments.
  • The forEach() method executes a provided function once for each array element.
  • The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
  • The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

My GitHub: https://github.com/Pilag6


Resources

Top comments (0)