Reverse a String, need help

Tell us what’s happening:

what’s the difference between the two, and why doesn’t the 2nd example work?

example 1

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

example 2
Your code so far


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

}

reverseString("hello");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string

is it because it calls the original argument every time I call a new method in a new line?

split actually returns an array, but since you are not assigning this returned value to anything, nothing happens and then when the next line is executed, you get an error, because str is not an array (it is still a string).

Every method returns a result. When you chain methods, the returned result is passed on to the next method in the chain until the last result is return by the return command.

str.split(""); returns an array but is not assigned anywhere and immediately garbage collected.
var str = str.split(""); here the return value( in this case an array) of the split method is assigned to the str variable.

In javascript you can reassign variables eventhough you’re using a method on the very same variable( in this case the str variable).

I recommend opening the console in the browser and trying for example “hello”.split(""); In the console you can see what the split method returns in the console without being assigned to a variable. Also create a function with a bunch of methods inside the function without assigning or returning them to see what happens.

2 Likes