DEV Community

Imran Shaik
Imran Shaik

Posted on

Reverse a string in JavaScript without using reverse()

Here is the JavaScript program to reverse a string without using the reverse() method

function reverseString(str){
    let reversed= '';
    for(i=str.length-1; i>0; i--){
    reversed += str[i];

}
return reversed;
}
const originalString = "Hello world";
const reveresedString = reverseString(originalString);

console.log("original String", originalString);
console.log("reversed string", reveresedString );
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. The function reverseString takes the input as string
  2. It iterates through the string from the last character to the first
  3. Each Character is appended to the reversed string in reverse order
  4. Finally the reversed string is return.

This Program avoids the use of reverse() and achieves the desired functionality.

Detailed: How it works.

  1. str[i]: Access the character at index i in the string str
  • for Example, if str == "Hello ": ** str[4]** is 'o' ** str[3]** is 'l'
  1. reversed += str[i]: this is shorthand for reversed = reversed + str[i]
    • it takes the current value or reversed, appends str[i] to it, and then updates reversed with this new value.

*Iterative Process: *
Let's break it down for str = "abc"

Initial state:

  • reversed=""(Empty string);
  • Loop start at i=2(last character of the string)

Iteration 1 (i=2);

  • reversed +=str[2] -> reversed = "" + "c" -> reversed ="c" Iteration 2 (i=1);
  • reversed +=str[1] -> reversed = "c" + "b" -> reversed = "cb" Iteration 3 (i=0);
  • reversed +=str[0] -> reversed = "cb" + "a" -> reversed ="cba"

Final Output:

  • reversed = "cba"

Why use += ?

The += operator simplifies the process of building the reversed string incrementally without needing an array or additional logic. It's efficient purpose in JavaScript

Modern auth, access management and billing for engineers.

Modern auth, access management and billing for engineers.

Secure and monetize your product from day one – with less code.

Get a free account

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Explore this compelling article, highly praised by the collaborative DEV Community. All developers, whether just starting out or already experienced, are invited to share insights and grow our collective expertise.

A quick “thank you” can lift someone’s spirits—drop your kudos in the comments!

On DEV, sharing experiences sparks innovation and strengthens our connections. If this post resonated with you, a brief note of appreciation goes a long way.

Get Started