String reverse in javascript

I had recently came upon a situation to work out string reverse in javascript, where it can be done with various techniques. I have tried some methods. The first one is using a standard for loop. The same can be achieved through a while loop also. Getting the length of the string and from there we can iterate down to the first character while collecting those in another variable and finally we get the string reversed.

The second one is using the split and join technique. We can split the string and make it an array and reverse it and again joining the array we end up with the reversed string.

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

Another thing I had tried is using,

Array.prototype.reverse.call(str,str);

And would you think this will work? The answer is no … Because javascript strings are immutable ie., they can’t be changed. Actually the array reverse method, reverse the array itself and so it will try to reverse the string itself and fails saying that the string is read only.

But ,

Array.prototype.slice.apply(str,[0,1]);

will work returning an array but the splice method fails as it will try to modify the object itself.

While trying the string reverse,for the first time I personally understand what is meant by immutable. Before this, it was just a word to me. 🙂