Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the significance of using: string.split("").reverse().join(")?

I want to say first. Very beginner. Be kind. However. I am attempting to reverse a string. Put a string into a function as an argument and reverse its order. For example 'hello' should return 'olleh', etc.

I have complete this by doing:

function revString(stringArg) {
    return stringArg.split("").reverse().join(");
}

However. By doing it like this:

function revString (stringArg) {
    stringArg.split("");
    stringArg.reverse();
    stringArg.join("");
    return stringArg;
}

The resulting output for the second function is that reverse() is not a function. Can someone tell me what the difference here is?

like image 512
user2613041 Avatar asked Nov 23 '25 16:11

user2613041


1 Answers

This is because .reverse() is used on the output of .split("").

Using .reverse() by itself doesn't work because the line before it doesn't directly change it unless you reassign it with stringArg = stringArg.split("");. The first line would return the array of characters but doesn't change stringArg directly.

So:

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

means to join all elements within the array whose elements are in reverse order based on the spliting of the string. In other words, .reverse() is used on stringArg.split(""), not just stringArg and same with .join(""): it is applied to stringArg.split("").reverse() not just stringArg.

Thus the solution would be:

function revString2 (stringArg) {
    a = stringArg.split("");
    b = a.reverse();
    c = b.join("");
    return c;
}
like image 81
Anthony Pham Avatar answered Nov 25 '25 09:11

Anthony Pham