Solution #1
function reverseString(str) {
return str.split('').reverse().join('');
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
str.split('')
: This line takes the input stringstr
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, ifstr
is"hello,"
this line would produce the array['h', 'e', 'l', 'l', 'o']
..reverse()
: After splitting the string into an array of characters, thereverse()
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 callingreverse()
, it becomes['o', 'l', 'l', 'e', 'h']
..join('')
: Finally, thejoin('')
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.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('');
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
return [...str]
: This part of the code uses the spread operator ([...]
) to convert the input stringstr
into an array of characters. This is done by splitting the string into individual characters and creating an array from them..reverse()
: After converting the string to an array of characters, thereverse()
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..join('')
: Finally, thejoin('')
method is called on the reversed array to concatenate its elements back together into a single string. The empty string '' passed as an argument tojoin()
specifies that there should be no separator between the characters, effectively merging them together.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;
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
let reversed = '';
: This line initializes an empty string reversed. This variable will be used to store the reversed version of the input string.for (let character of str) { ... }
: This is a for...of loop that iterates through each character in the input stringstr
. It goes through the string one character at a time.reversed = character + reversed;
: Inside the loop, the currentcharacter
(a single character fromstr
) is concatenated to the beginning of thereversed
string. This effectively builds thereversed
string in reverse order. For example, if the input string is"Hello,"
the loop will first add"o"
toreversed
, then"lo,"
and so on until the entire string is reversed.The loop continues until it has processed all characters in the input string.
Finally, after the loop completes, the
reversed
string contains the reversed version of the input string, andreturn 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;
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
let reversed = '';
: This line initializes an empty string variable called reversed. This variable will be used to store the reversed string.for (let i = str.length - 1; i >= 0; i--)
{: This line starts a for loop. It initializes a loop variablei
to the length of the input stringstr
minus one (since array indices in JavaScript are zero-based), and the loop continues as long asi
is greater than or equal to 0. In each iteration, it decrementsi
by 1.reversed += str[i];
: Inside the loop, this line appends the character at the current indexi
of the input stringstr
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.The for loop continues until it has iterated through all the characters in the input string, effectively reversing the order of the characters.
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;
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
let reversed = '';
: This line initializes an empty string reversed, which will eventually hold the reversed version of the input string.str.split('')
: This part of the code splits the input stringstr
into an array of individual characters. Thesplit('')
method is used with an empty string as the separator, which effectively splits the string into an array of characters.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 thereversed
string. Thecharacter + reversed
expression concatenates the current character with the existingreversed
string. Since we are adding characters to the beginning ofreversed
, 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'After the loop has finished processing all the characters in the input string, the
reversed
variable will contain the reversed string.Finally,
return reversed;
returns the reversed string as the result of thereverseString
function.
Solution #6
function reverseString(str) {
let reversed = "";
str.split("").map((character) => (reversed = character + reversed));
return reversed;
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
let reversed = '';
: This line initializes an empty string variable called reversed. This variable will be used to store the reversed string.str.split('')
: This part of the code splits the input stringstr
into an array of individual characters. It does so by calling thesplit('')
method on the string with an empty string as the separator. This effectively separates each character in the string into an array element..map(character => reversed = character + reversed)
: This part of the code uses themap
function to iterate through each character in the array of characters created in the previous step. For each character, the code performs the following:character
: This represents the current character in the iteration.reversed = character + reversed
: This code concatenates the current character with thereversed
string. It adds the current character to the beginning of thereversed
string. This effectively reverses the order of characters since each character is added to the start of reversed.return reversed;
: After themap
function has processed all characters and reversed the string, the function returns thereversed
string as the result.
Solution #7
function reverseString(str) {
return str.split('').reduce((reversed, character) => character + reversed, '');
}
Test
console.log(reverseString('hello')); // olleh
Step by Step
str.split('')
: This line takes the input stringstr
and uses thesplit
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, ifstr
is"hello,"
the result will be['h', 'e', 'l', 'l', 'o']
..reduce((reversed, character) => character + reversed, '')
: After splitting the string into an array of characters, thereduce
method is called on the array. Thereduce
method is used to iterate through the array and accumulate a single value based on the elements in the array.(reversed, character) => character + reversed
: This is an arrow function used as the callback function for reduce. It takes two parameters:reversed
andcharacter
.reversed
is the accumulating value, which starts as an empty string('')
, andcharacter
is the current character being processed from the array.character + reversed
: In each iteration ofreduce
, this expression concatenates the current character (character
) with the accumulated reversed string (reversed
). Thecharacter
is added in front of the existingreversed
string. This effectively builds the reversed version of the input string.The result of the
reduce
operation is the reversed string, which is returned by the reverseString
function.So, when you call
reverseString("hello")
, it splits the string into an array of characters (['h', 'e', 'l', 'l', 'o']
) and then usesreduce
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
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
- https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/
Top comments (0)