.join not working as expected

I’m trying to understand a palindrome problem and I have written the code below. Why does .join not work by itself but works when embedded within a console log?

var str = 'hello dave';

var chars = str.split('');
console.log(chars);
chars.reverse();
console.log(chars);
chars.join(''); // Why does this step not result in the joined Array being print below?
console.log(chars); // Why does it not produce the joing step above.
console.log(chars.join('')); //Why does including it in a console log produce the correct output?

//This is the output from the above code
> Array ["h", "e", "l", "l", "o", " ", "d", "a", "v", "e"]
> Array ["e", "v", "a", "d", " ", "o", "l", "l", "e", "h"]
> Array ["e", "v", "a", "d", " ", "o", "l", "l", "e", "h"]
> "evad olleh"

The join method returns a new string and does not change the original array.

Because join returns a string and does not mutate the original array (chars). You can assign the result to a variable and console.log the variable.

Below works as expected. Obvious that it wouldn’t change an array to a string now you mention it! Thanks guys!

var str = 'hello dave';

var chars = str.split('');
console.log(chars);
chars.reverse();
console.log(chars);
newString = chars.join('');
console.log(newString);
console.log(chars.join(''));


1 Like