Reverse a String In-Place Without Built-In Functions in JavaScript

How can I use JavaScript reverse string techniques to reverse a string in-place within a function, ensuring it is returned without relying on built-in functions like .reverse() or .charAt()?

With my experience in JavaScript, one of the simplest ways to reverse a string manually is to use a for loop. You can break the string into an array of characters, then swap the first and last, moving toward the center. This method avoids built-in functions like .reverse() or .charAt() and works efficiently in-place.

function reverseString(str) {
    const arr = Array.from(str);
    for (let i = 0; i < Math.floor(arr.length / 2); i++) {
        const temp = arr[i];
        arr[i] = arr[arr.length - 1 - i];
        arr[arr.length - 1 - i] = temp;
    }
    return arr.join('');
}

const reversed = reverseString("hello");
console.log(reversed); // "olleh"

This is a practical approach using basic loops and arrays in JavaScript to reverse strings.

recursion offers a more elegant, mathematical approach to solving the problem. If you’re familiar with recursion, you can reverse a string by iteratively cutting off the last character and appending it to the result. No array conversion is necessary, and this method can be more readable, especially for those comfortable with recursion.

function reverseString(str) {
    if (str === "") return "";
    return str[str.length - 1] + reverseString(str.slice(0, str.length - 1));
}

const reversed = reverseString("hello");
console.log(reversed); // "olleh"

This technique works by breaking down the string piece by piece, relying on the function call stack to build the reversed string.

if you’re interested in data structures, we can use a stack to reverse a string. By pushing each character into a stack (an array in this case) and then popping them off, you can simulate the Last In, First Out (LIFO) behavior to reverse the string. This approach is similar to recursion in that it takes advantage of stack-like behavior, but we manage the stack ourselves.

function reverseString(str) {
    const stack = [];
    for (let char of str) {
        stack.push(char);
    }
    let reversed = '';
    while (stack.length > 0) {
        reversed += stack.pop();
    }
    return reversed;
}

const reversed = reverseString("hello");
console.log(reversed); // "olleh"

The stack approach emphasizes the use of memory to reverse the string, allowing a clear visualization of how elements are processed.