Array.reverse() seems to not work?

Array.reverse() seems to not work?


Can anyone explain why this code behaves this way?

function reverseString(str) {
  var chars = str.split();
  return chars;


Output is:


After the first line, chars is an array of one element [ ‘dog’ ]. Why? Because you did not specify a delimiter. See the split documentation for more information.

After the second line, chars is still an array of one element in reversed order, so it is just the same array [ ‘dog’ ]

After the third line, chars does not change, because the join function does not affect the array on which it is called. It returns a string of the joined array. See the join documentation for more information.

In the end, the function returns [ ‘dog’]


Ah, so .split() on a string creates a single element array? I thought it split the string into an array of characters.

God I miss real Java. Never thought I would say that…

Thanks Randell


To do that you would need to write str.split(’’)