Reverse a String error

Tell us what’s happening:

why does it works only when it is saved in str like

str=str.split("");// it needs str= to save?
then
str.reverse();//it reverses automatically

str=str.join(""); // same here it needs to be saved in str.

why does this does not work

str.split("");
str.reverse();
str.join("");

gives error// reverse() undefined.

Your code so far

function reverseString(str) {
  str=str.split("");
  str.reverse();
  str=str.join("");
  
  
  
  return str;
}

reverseString("hello Babu rao!@");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0.

Link to the challenge:

It doesn’t work because .split() doesn’t change str to an array, but rather makes a new array out of it while preserving the original string (all string functions preserve the original string). Now when you attempt str.reverse(), you get an error because strings don’t have a .reverse() function (arrays do however).

Comparing with your first code snippet, you make an array out of str using str.split(''), then store the result in the same str variable. Now str is an array, and thus str.reverse() works as expected. The idea is the same with str.join(''). It makes a string out of an array, which you store in the same str variable.

1 Like

if i do not save it i.e.
str=str.split(" ");
then on next line original str passed to function is used. hence the error.

As the poster above said the .split method returns a new array. You can then use the .reverse() and .join() methods on the new array and return the new string you have created.

Something like this…

function reverseString(str) {
  var newArr = str.split(""); //returns ['h', 'e', 'l', 'l', 'o']
  newArr.reverse(); //returns ['o', 'l', 'l', 'e', 'h']
  var newStr = newArr.join(""); //returns 'olleh'
  return newStr;
}

reverseString("hello");

Your explanation is easy to understand the process.
I wonder your example code has an error at newArr.reserve().
Error message is “TypeError: newArr.reserve is not a function”.
Why is that?

It’s reverse, not reserve

Spelling wrong is my bad…
Thank you all!