Reverse string without using reverse()

Chrome console gave me the same result when executing these two snippets.
I think that I should use let i = Array.length -1 instead of i = Array.length right?

function reverse(string){
  let newArray = [];
  let Array = string.split('');
  
  for(let i = Array.length; i>-1; i--){
    newArray.push(Array[i]);
  }
  return newArray.join('');
}
reverse('racecar');
function reverse(string){
  let newArray = [];
  let Array = string.split('');
  
  for(let i = Array.length-1; i>-1; i--){
    newArray.push(Array[i]);
  }
  return newArray.join('');
}
reverse('racecar')

because a 3 letter string ends with string[2] so I should be adding in element at [2] instead of [3] right?
but the result is the same cos I was adding in one empty element???

Is my speculation correct?

yeah, I just saw a youtube video and realised that you can do the same stuff to a string.

function reverse(string){
  let result = '';
  for(let i = string.length - 1; i>=0; i--){
    result = result + string[i];
  }
  return result;
}
reverse('hello');

how do I use a for…of loop to do the same thing??? reverse a string I mean…

Instead of this thread turning into a thread of all possible solutions for this challenge, I will send you a private message.

Basically, it would not be very advantageous to use a for of loop here. A for in loop would definitely work though.

1 Like