Reverse a String - Why doesn't my code work?

Reverse a String - Why doesn't my code work?
0.0 0

#1

Hi All

After fiddling with my code for the Reverse a String challenge, I solved the problem eventually. But I’m not sure why my first attempt didn’t work (I’m very new to programming).

Here is my first attempt:

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

reverseString("hello");

And here is what worked:

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

reverseString("hello");

I understand why my final solution worked, but I would also like to understand why my first attempt didn’t work. Can anyone explain?

Many thanks,
Mitch.


#2

In JavaScript, functions are functional, meaning that they return a value and don’t “mutate” a data type such as a string. So in the first attempt, the returned​ string from the result of the split, reverse, and join is actually lost because you didn’t save it.

The “return str” actually returns the original​ argument string unmodified, because it was never changed to begin with. The split, reverse, and join are all functional, meaning that a new string is returned by each method call.


#3

step through it here https://goo.gl/pnHUf0 … look at the reverseString block on right hand side of window that appears on step 2 look at console.output on right hand side at top on step 3 and look again at reverseString block
uncomment the commented line of code and step through again


#4

Basically what astv said;

Strings are immutable so the functions you called will return a string but have no effect on the original. I believe if you had var a = in front of your function call and then return a; it would have worked.


#5

str = str.split('').reverse().join('');
return str;

As people have said above, you need to save changes to your variable.


#6

you’re returning the argument.
function reverseString(str) {

return str;
}


#7

Thanks all, appreciate the feedback.