Hi everyone,
I am trying to solve the Basic Algorithm Scripting: Reverse a String Challenge.
I have attempted using the code below, but I am not sure why .join() does not link the individual elements together. I have looked at other solutions and found that most of them declared a new variable to store the .reverse() array before using .join()
I am assuming that after implementing arrStr.reverse(), arrStr now holds the array of [“o”,“l”,“l”,“e”,“h”]. Therefore, I am not sure why .join() doesn’t work on arrStr.
Here is my code:
function reverseString(str) {
var arrStr = str.split("");
arrStr.reverse();
arrStr.join("");
return arrStr;
reverseString("hello");
Thanks!
Instead of doing the operations in separate lines, you should chain them, meaning that you could do something like this: str.split(“”).reverse().join(“”)
And the reason is not working for you is because join()
doesn’t change the array, it will just return it. So you need to chain it, or save it in another variable.
This is the official definition of join:
The join() method joins the elements of an array into a string, and returns the string.
2 Likes
yes I understand I can do that, but I am not sure why my solution wouldn’t work?
I updated my answer above.
Thank you for your prompt response! Much appreciated!
1 Like
Pleasure to help. What you need to learn is that there are some methods on the array which is changhing that particular array (like reverse, splice, etc).
But some of the functions (like map, join, filter, etc), won’t change the array, but instead will return a new array.