Reverse string without using reverse()

Reverse string without using reverse()
0

#1

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?


#2

You should really be using Array.length -1, because before you join newArr, it looks like:

[ undefined, 'r', 'a', 'c', 'e', 'c', 'a', 'r' ]

It seems the join method protects you and ignores any elements which have values of undefined or null when creating the string.

Did you consider solving this challenge without splitting string into an array? You could create a blank string and then concatenate the characters inside the for loop.


#3

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');

#4

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


#5

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.