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.
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?