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];
  return reverse;


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:

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:

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];
  return revstr;

1 Like