Aside from the straightforward answer that Ash gave you, you can try an alternative if the reverse() method is not made available to you or you are not allowed to use it.
- You can create an empty string called
reversed.
- To iterate through the
string that was provided and for each character in that string, you are going to take that character and add it to the start of reversed
- Then you are going to return the variable
reversed.
So you are taking each character out of the original string and sticking into the new one, one by one.
function reverse(string) {
let reversed = '';
}
So I have declared a temporary variable called reversed and assigned it an empty string. This is the temporary variable I have assembled over time as I iterate through the string variable.
Now I need a for loop, but instead of a classic for loop I am going to use the ES2015 for...of loop.
function reverse(string) {
let reversed = '';
for (let character of string) {
}
}
Notice the use of the let variable identifier? Its because I am going to reassign reversed like so:
function reverse(string) {
let reversed = '';
for (let character of string) {
reversed = character + reversed;
}
}
Lastly, as outlined in step 3, I return the new assignment of reversed.
function reverse(string) {
let reversed = '';
for (let character of string) {
reversed = character + reversed;
}
return reversed;
}
So I am taking a temporary variable that is redeclared every single time through this loop of character. Then I say of and the iterable object that I want to iterate through, in this case, all the characters of the string.
So I will iterate through each character, one by one and then set each character equal to temporary variable of character and then I take that character and add it on to the start of string reversed and after the entire loop I return the string reversed.
You can use this in place of the classic for loop just keep in mind you will not be able to use this syntax if you are required to iterate through every third element. In such a case, you have to use the classic for loop.
forstatement condition is correct?.split(' ').reverse().join(' ')