JavaScript: Reverse a String without Built-in reverse() Function

1. Introduction

Reversing a string is a classic problem in computer science and programming. In this tutorial, we will explore a simple way to reverse a string in JavaScript without using the built-in reverse() method, which is typically applied to arrays and not directly to strings.

2. Program Overview

We will create a function named reverseString that takes a string as its parameter. This function will iterate over the string, building a new reversed version of it. Finally, the function will return the reversed string.

3. Code Program

// Function to reverse a string without using reverse()
function reverseString(str) {
    // Create an empty string to store the reversed result
    let reversed = '';

    // Iterate over the original string from end to start
    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }

    // Return the reversed string
    return reversed;
}

// Test the function
let example1 = reverseString('hello');  // Expected: 'olleh'
let example2 = reverseString('JavaScript');  // Expected: 'tpircSavaJ'

console.log(example1);
console.log(example2);

Output:

olleh
tpircSavaJ

4. Step By Step Explanation

1. Function Definition: We begin by defining a function named reverseString which takes a single parameter str representing the string to be reversed.

2. Initialization: Inside the function, we declare an empty string named reversed that will store the characters of the reversed string.

3. Reversing Logic: We use a for loop to iterate through the original string from its end towards the start. For each character, we append it to our reversed string.

4. Final Result: After processing all characters, the reversed string will contain the original string but in reverse order. We then return this reversed string.

5. Tests: We test our function using two example strings and display the results using console.log.

By avoiding built-in methods and using simple loops, we gain a better understanding of the logic and operations behind string reversal.

Comments