# Basic Algorithm Scripting - Reverse a String

Can anyone explain to me why this works:

function reverseString(str) {
let splitIt = str.split(‘’);
splitIt.reverse();
return splitIt = splitIt.join(‘’);
}

reverseString(“hello”);

but this does not?

function reverseString(str) {
let splitIt = str.split(‘’);
splitIt.reverse();
splitIt.join(‘’);
return splitIt;
}

reverseString(“hello”);

The first one will split, reverse, then combine. The second will only split and reverse.

try to run this version of 2nd code
And consider research about join method

``````function reverseString(str) {
let splitIt = str.split('');
console.log(splitIt);//[ 'h', 'e', 'l', 'l', 'o' ]
splitIt.reverse();
console.log(splitIt);//[ 'o', 'l', 'l', 'e', 'h' ]
splitIt.join('');
console.log(splitIt);//[ 'o', 'l', 'l', 'e', 'h' ]
return splitIt;
}

console.log(reverseString('hello'));
``````

I ran the same log to try and trouble shoot, I am just having a hard time understanding the intricacies of .join.

That should give you more ideas:

``````function reverseString(str) {
let splitIt = str.split('');
console.log(splitIt);//[ 'h', 'e', 'l', 'l', 'o' ]
splitIt.reverse();
console.log(splitIt);//[ 'o', 'l', 'l', 'e', 'h' ]
a = splitIt.join('');
console.log(splitIt);//[ 'o', 'l', 'l', 'e', 'h' ]
console.log(a);//olleh
return splitIt;
}

console.log(reverseString('hello'));
``````

Some methods are changing existing arrays, some methods are creating new stuff.
If you are dealing with new methods, either do research on MDN or somewhere else, or do crazy console-logging like I did above to understand what’s going on

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.