Other ways to reverse a string

Tell us what’s happening:
The very bottom is my code that reverses a string. I was curious what other ways there were to achieve the same goal. Here are a few questions I had about ways to do things.

  • Is it possible to convert str to an array without using a second variable?
    When I do this
 function reverseString(str) {
  const STR3 = [];
  let placeholder;
  str = Array.from(str);
  
  
  for (let i = 0; i < str.length; i++){
  	placeHolder = str.shift();
    STR3.unshift(placeHolder);
  }
  
  return STR3.join("");
}

console.log(reverseString("hello"));

I get a return of “leh”, where did “ol” go?

  • When I declare STR3 = [] do I get an array with an undefined size? Is it better to only create an array of the specific size if I know what size I want it to be beforehand? Why?
  • I assume by the nature of how memory is stored sequentially in an array it makes it impossible for me to .shift() the second value of the array and then .unshift() back to the front in a for loop of str.length - 1?

Thanks for your time!

Your code so far


function reverseString(str) {
const STR2 = Array.from(str);
const STR3 = [];
let placeHolder;


for (let i = 0; i < str.length; i++){
	placeHolder = STR2.shift();
  STR3.unshift(placeHolder);
}

return STR3.join("");
}

console.log(reverseString("hello"));

  **Your browser information:**

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

Challenge: Reverse a String

Link to the challenge:

when i tried your provided code from ‘your code so far’ it’s showing correct output, and now you want to accomplish it differently, is that it?

just want to be sure, thanks :slight_smile:

Yeah, I found a solution. I just wanted to know what some other good ways of solving the problems are, as well as answers to my above questions. :grinning:

Just to try and reinforce my learning.

hurraah!! well done then and yeah its always better to know different ways of doing things, you never know which techniques come to rescue at later times!! kudos :slight_smile:

Hi @Mutiplify ,
I will try my best and help you with what I can.

From what I can see in your code, your loop is only running 3 times, while it needs to run 5 times.
The shift() method removes elements from the str array, and thus changing its length.
By the 3rd iteration of the for loop, the index i is equal to the length of the str array, which stops the for loop.
Storing the length of the array in a variable at the beginning can help solve this :

 let strLength = str.length;

And so the for loop becomes :

for (let i = 0; i < strLength; i++){ .. }

Also make sure that it is placeHolder with a H on line 3.
I hope this will help.

There are many ways to do many things, this includes reversing a string. If you click on the “get a hint” button in the challenge, you should find some other suggested ways to achieve that.
Strings are immutable, which means you cant change their value, but you can change the value of the variable that holds them, or you can use another variable, to store another value, derived of the string you work with.
Converting a string to an array is good way to get a different string out of it, as arrats are easier to work with, they offer very powerful methods and since they can be mutated, you dont always have to use additional variables to store values, or make too complex logics.
When you say arr = [] you simply create an empty array. From there on, you can use array methods on that variable and add contents. There is no particular defined size arrays should have. Their size changes based on how many elements of data you store in them.
Its important to really know the details of methods you use, in order to use the right methods for your needs. shift and unshift mutate arrays, meaning, they change the contents of the array you attach them to. Those methods also return the element they applied on. For example

const arr= [1, 2, 3, 4]

const shift = arr.shift()
console.log(arr)      // logs [ 2, 3, 4 ]
console.log(shift)    // logs 1

const unshift = arr.unshift(5)
console.log(arr)      // logs [ 5, 2, 3, 4 ]
console.log(unshift)  //logs 4

This conde illustrates well, how both mehtods change the array they apply on, but also return that value, if we wish to use it. Or we could just say arr.shift(), without assigning the value returned to a variable, and simply remove the element, not caring of its value anymore.
There are also the other type of array methods, which do not mutate the array, but only return a value. Such are slice and concat. The first can give us part of an array, the other would return the array with additional elements attached to it, but neither would modify the original array and to really make use of them, we want to put the value those mehtods return somewhere.
Idk if this explanation can be of much use for your particular challenge, but i hope it does assist you understand better those particular details working with strings and array that all of us face occasionally and especially in our beginning.

1 Like

Considering the challenge allows the use of the reverse method, that would be a clean approach. You do not need any variable with that you just split the string, reverse it and then join it back again.

Another option is to loop the string in reverse and build the new string using that loop.

1 Like

From what I can see in your code, your loop is only running 3 times, while it needs to run 5 times.
The shift() method removes elements from the str array, and thus changing its length.
By the 3rd iteration of the for loop, the index i is equal to the length of the str array, which stops the for loop.

I can’t believe I didn’t realize this! Thank you, that makes complete sense, I just need to walk through things a little more slowly.

Thanks everyone for your responses I appreciate the support!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.