Complete the code to reverse a string using built-in methods.
const reversed = str.split('')[1].join(''); console.log(reversed);
The reverse() method reverses the array elements, which helps reverse the string after splitting it.
Complete the code to reverse a string using a for loop.
let reversed = ''; for (let i = str.length - 1; i [1] 0; i--) { reversed += str[i]; } console.log(reversed);
The loop starts from the last index and continues while i is greater than or equal to 0 to include the first character.
Fix the error in swapping characters to reverse a string in place using an array.
const arr = str.split(''); for (let i = 0; i < arr.length / 2; i++) { const temp = arr[i]; arr[i] = arr[arr.length - 1 - [1]]; arr[arr.length - 1 - i] = temp; } const reversed = arr.join(''); console.log(reversed);
The index to swap with is arr.length - 1 - i, so i must be used in the expression.
Fill both blanks to create a function that reverses a string using recursion.
function reverse(str: string): string {
if (str.length [1] 0) return '';
return str.charAt(str.length - 1) + reverse(str.[2](0, -1));
}The base case checks if the string length is zero using ===. The recursive call uses slice(0, -1) to remove the last character.
Fill all three blanks to create a one-liner that reverses a string using reduce.
const reversed = str.split('')[1]((acc, char) => char [2] acc, [3]); console.log(reversed);
The reduce method accumulates characters in reverse order by adding the current character before the accumulator. The initial value is an empty string.
