# ** Explanation Needed ** Reverse a String

Solution:

``````function reverseString(str) {
for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
``````

Could someone please explain to me this line of code:

``````for (var reversedStr = "", i = str.length - 1; i >= 0; i--)
``````

The explanation on the guide says:

• Starting at the last character of the string passed to the function, you build a new string `reversedStr` from `str` .
1. Why is var reversedStr = `" "`?
2. How does it start at the last character of the string?
3. What is the role of `i--` here?

This is a clearer version:

``````function reverseString(str) {
let reversedStr = ""
for (let i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
``````
1 Like

Side note - you were just on the previous algorithm challenge. I wouldnâ€™t jump right to the answers before figuring out how to do the algorithm challenges for yourself. This section is really where you start to learn how to become a programmer.

2 Likes

I still donâ€™t understand the following:

``````for (let i = str.length - 1; i >= 0; i--)
``````

From my understanding, the first condition of for loop is the starting point, the second condition is the ending point, and the third condition is increment/decrement.

I understand that `i--` indicates that the loop is decrementing by 1.

But how does `i = str.length - 1; i >= 0;` reverses the string?

What is `str[str.length - 1]`?

Itâ€™s best to think of the clauses in a `for` loop as loop (index) initializtion; loop (index) test; index adjustment rather than as starting and ending points. Each clause can be arbitrarily complex (but you should keep them as simple as possible).

In fact, the code blocks

``````for(let i=0; i<some_limit; i++) {
// do stuff
}
``````

and

``````let i=0;
while(i<some_limit) {
// do stuff
i++;
}
``````

are functionally equivalent.

With that out of the way, to directly answer your confusion, the `for` loop in the posted solution doesnâ€™t reverse a string. So what does it do? If you can answer that, youâ€™ll be well on your way to understanding.

jrm

It takes the index of the final character in the string and iterates the string till it reaches index 0?

Yes, looks like you got it!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.