Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Reversing a string using for loop in JavaScript
We are required to write a JavaScript function that takes in a string as the only argument. The function should construct a new reversed string based on the input string using a for loop.
Syntax
for (let i = string.length - 1; i >= 0; i--) {
reversedString += string[i];
}
Example
Following is the code −
const str = 'this is the original string';
const reverseString = (str = '') => {
let reverse = '';
const { length: len } = str;
for(let i = len - 1; i >= 0; i--){
reverse += str[i];
};
return reverse;
};
console.log(reverseString(str));
Output
Following is the output on console −
gnirts lanigiro eht si siht
How It Works
The function uses destructuring to get the string length, then iterates backwards from the last character to the first. Each character is concatenated to build the reversed string.
Alternative Approach
Here's a simpler version without destructuring:
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString('Hello World'));
console.log(reverseString('JavaScript'));
dlroW olleH tpircSavaJ
Conclusion
Using a for loop to reverse strings is straightforward and efficient. Start from the last index and concatenate characters in reverse order to build the new string.
Advertisements
