Today we are going to learn how to reverse a string in Javascript.
I could use a few built-in methods to achieve this but I’ll use a for loop because it’s funner!
The first thing I’ll do is create a function called reverseStringLoop and give it a parameter called str (the string we will be reversing).
In this example the string we will be reversing is “world.”
I’ll create an empty string called reversed and use the let keyword because the empty string will change over time.
The first iteration of the for loop will get the last letter of the string and add it to reversed (“” + d).
The second iteration will get the second to the last letter of the string and add it to reversed (“” + d + l).
We will repeat this process for every letter of the string then simply return the reversed string (return reversed).
Here is all of the code you will need to properly reverse the string:
function reverseStringLoop(str) {
let reversed = ”;
for (let i = str.length – 1; i >= 0; i–) {
reversed += str[i];
}
return reversed;
}
// Example usage
const originalString2 = ‘world’;
const reversedString2 = reverseStringLoop(originalString2);
console.log(reversedString2); // Output: ‘dlrow’
The function reverseStringLoop has a time complexity of O(n) and a space complexity of O(n), where ‘n’ is the length of the input string.
Time Complexity: O(n):
The time complexity is linear because the code iterates through each character of the input string once. The for loop runs n times, and within the loop, the operations (accessing a character by index and string concatenation) take constant time. Therefore, the total time required grows proportionally to the size of the input string.
Space Complexity: O(n):
The space complexity is also linear because a new string, reversed, is created to store the result. In each iteration of the loop, a character is appended to reversed, and at the end of the loop, the reversed string will have the same length as the original string. This means the memory usage scales directly with the size of the input string.
In JavaScript, string concatenation using += can sometimes create new strings in memory, but for a simple loop like this, the overall space required for the new string is proportional to the input size.
Useful links below:
Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service
Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2
Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff
Buy me a coffee https://buymeacoffee.com/tyronneratcliff



