1

Using just the parameter fails but using a variable works, what is the difference?

<script type="text/javascript">
    function Person(name) {
        //Throws error - name.reverse is not a function
        name.split("");
        name.reverse();
        name.join("");

        // Works
        var splitString = name.split("");
        var reverseString = splitString.reverse();
        var joinString = reverseString.join("");
        return joinString;
    }
    document.write(Person("Joe"));
</script>

3 Answers 3

3

A string cannot be reversed using name.reverse(). reverse() is a method of array. this is the solution

function Person(name) {
    //Throws error - name.reverse is not a function
    name = name.split("");
    name = name.reverse();
    name = name.join("");
    return name;
}
Sign up to request clarification or add additional context in comments.

Comments

2

From MDN documentation of split:

Return value

An array of strings split at each point where the separator occurs in the given string.

It returns an array, does not change the type of variable in-place... Actually, no operation I know of changes the type of variable in-place.

return name.split("").reverse().join("");

Comments

1

The point is what happens to name in the first three function calls. The answer is absolutely nothing.

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

This says "split name, then discard the result, then reverse it and discard the result, then join it and discard the result". name never ceases to be the original string. And, crucially, reverse and join are not string functions but array functions.

Now let's look at the other calls.

var splitString = name.split("");
var reverseString = splitString.reverse();
var joinString = reverseString.join("");
return joinString;

Here you are actually using the results of the function calls. You are saying "split the name into an array of characters and call this array splitString, then reverse the array of characters and call it reverseString, then join that array together and call it joinString, then return joinString.

Note that splitString and reverseString are, technically, not strings. They are arrays, which is why join and reverse work.

The other option, of course, is to chain it:

return name.split("").reverse().join("");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.