How do you JavaScript reverse string in-place within a function, using a return statement, without relying on built-in methods?

How do you JavaScript reverse string in-place within a function, using a return statement, without relying on built-in methods like .reverse() or .charAt()?

To reverse a string in JavaScript without using built-in methods like .reverse() or .charAt(), you can achieve this manually by iterating through the string and reconstructing it.

You can loop/ iterate through the string from the end to the beginning and build a new string by appending each character in reverse order.

function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString("hello")); // Output: "olleh"

This method uses two pointers, one starting at the beginning and the other at the end of the string. The characters are swapped until they meet in the middle.

function reverseString(str) {
let arr = str.split('');
let left = 0;
let right = arr.length - 1;
while (left < right) {
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr.join('');
}
console.log(reverseString("hello")); // Output: "olleh"

This solution uses recursion to reverse the string. It takes the first character and appends it to the reverse of the remaining string.

function reverseString(str) {
if (str === "") {
return "";
} else {
return reverseString(str.substr(1)) + str[0];
}
}
console.log(reverseString("hello")); // Output: "olleh"

Each of these solutions manually reverses the string without relying on the .reverse() or .charAt() methods, and each addresses the task of javascript reverse string effectively.