Reverse a String in JavaScript without using Inbuilt Function

In this example, you will learn how to reverse a string in JavaScript without using any inbuilt function.

To achieve this, we will first create an empty string and then one by one append each character of the original string into this empty string but in the reversed order:

// JavaScript program to reverse a string

function reverseStr(str){
    
    // Create empty string
    let newStr = "";
    
    // Append each character in reversed order
    for(let i = str.length-1; i>=0 ; i--){
        newStr = newStr + str[i];
    }
    
    return newStr;
}

// Original string
let str = "abcdef";

str = reverseStr(str);

// Print reversed string
console.log(str);

Output:

fedcba

In the above program, we have a string “abcdef”. We want to reverse this string, therefore, we passed it to the reverseStr() function.

Inside the reverseStr() function,

  • We first created an empty string and assigned it to the variable newStr.
  • Created a for loop to iterate over the original string in reverse order. It means, in the first iteration, the last character of the original string gets appended to newStr. In the second iteration, the second last character, and so on.
  • The loop continues until the value of variable i becomes 0.
  • At last, the function returns the reversed string.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts