Reverse a String - JavaScript

Tell us what’s happening:
I have read the split,reverse and join methods but if i wanted to do it with a for loop then what is wrong with my function?

It’s returning “NaNolleh” , not “olleh” . If string “hello” is given.
Also if i initiate my i counter with
i = str.length - 1 ,
then the output changes and gives me “Undefinedolleh”.
I would like some help here please to explain this.

Your code so far


function reverseString(str) {
  let reverse;
  for(let i=str.length; i>=0; i--){
   reverse=reverse + str[i];
  }
  console.log(reverse)
  return reverse;
}

reverseString("hello");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

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

As you have not given an initial value to reverse, its initial value is undefined

str[str.length] is also undefined (last index is str.length - 1)

undefined + undefined gives NaN

If you make the loop start with let i = str.length - 1 then only the first issue stay.

When a string starts getting concatenated NaN or undefined are converted to a string, and letters are concatenated to it.

If you want to see this happening, use: http://pythontutor.com/javascript.html

1 Like

Oh! my bad. Thanks a lot!

I got the code running with

function reverseString(str) {
  
  let revstr="";
  
  for(let i=str.length-1; i>=0; i--){
   revstr=revstr + str[i];
  }
  console.log(revstr)
  return revstr;
}

reverseString("hello");
1 Like