Reverse a String (please help me understand how my code works?)

Tell us what’s happening:
So you can see my code and that works, what I don’t get is the str.length part. It used to be rev.length part on the count that rev = […str] which means rev is an array with h e l l o as elements which means, more than 1 length but if I do that, it doesn’t work. What works is str.length but str only has one length because it is hello, which is one element. So how come the more seemingly logical rev.length doesn’t work but the seemingly illogical str.length works??

rev.length returns oll
str.length return olleh (correct result)
Your code so far


function reverseString(str) {
    let rev = [...str];
    let rev2 = "";
 
 for (let i = 0; i < str.length; i++) {
 
   rev2 = rev2 + rev.pop();
 }
 return rev2;
}

reverseString("hello");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string

Can you give an example of what it looked like when it wasn’t working.

But as far as str.length goes, in this case, you are asking for the length of the string, which measures the number of letters in a string.
When you are calling .length on an array, it gives you the number of elements in the array.

So for example:
“hello”.length => 5
[“hello”].length => 1

Makes sense?

If the only thing that you’ve changed is that you used rev.length in the for loop, then your problems were probably coming from the fact that you were were poping rev inside the loop. That means that it’s length was 1 less every time it was checked:

General rule: do not mutate an array that you are iterating over.

when it wasn’t working, it would only get oll instead of olleh (rev.length compared to str.length) I keep forgetting the basics. From your explanation, I guess that would work since I’m not asking for the number of arrays but rather the number of string inside a variable. I still don’t know why rev.length stops at oll though.

holy shit you’re right! O.O should it have been something like […rev.length]? will that even work? There’s a way to use … so that an array doesn’t get affected right?

You’re not using i, so instead of doing for (let i = 0; i < rev.length; i++), you can just do a while(rev.length < 0) to keep going until you have removed all items from the array.

thanks! I’m just about to use a while loop, hopefully I get used to all the loops available, I’ll keep this in mind! 8D

thought id give it a try. heres what i got. i left comments too

1 Like

thanks for taking the time dude! :smiley: