dev-resources.site
for different kinds of informations.
Reverse a string in JavaScript without using reverse()
Published at
12/22/2024
Categories
javascript
react
angular
interview
Author
Imran Shaik
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 );
Explanation
- The function reverseString takes the input as string
- It iterates through the string from the last character to the first
- Each Character is appended to the reversed string in reverse order
- Finally the reversed string is return.
This Program avoids the use of reverse() and achieves the desired functionality.
Detailed: How it works.
- 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'
-
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
Articles
6 articles in total
Explain Closure in detail ?
read article
What is generator function in JavaScript? and How does it work?
read article
Reverse a string in JavaScript without using reverse()
currently reading
Different Ways to find maximum number in javascript
read article
How do we sort an Array in Javascript without Sort function?
read article
Different ways to create Objects in Javascipt
read article
Featured ones: