const str = "hello"; const reversed = str.split('').reverse().join(''); console.log(reversed);
The code splits the string into characters, reverses the array, then joins it back into a string. So "hello" becomes "olleh".
const str = "abcde"; let reversed = ""; for(let i = str.length - 1; i >= 0; i--) { reversed += str[i]; } console.log(reversed);
The loop goes from the last character to the first, building the reversed string character by character.
function reverseString(s: string): string {
if (s.length === 0) return s;
return reverseString(s.substring(1)) + s[0];
}
console.log(reverseString("test"));The function correctly reverses the string recursively by calling itself on the substring from index 1 and appending the first character at the end. It returns "tset" for "test".
const str = "world"; const reversed = [...str].reduce((acc, char) => char + acc, ''); console.log(reversed);
The reduce function prepends each character to the accumulator, effectively reversing the string.
Manual reversal using string concatenation inside a loop can be O(n^2) because strings are immutable and concatenation creates new strings each time. Built-in methods like split, reverse, and join operate on arrays and are optimized to run in O(n).
