How to use for Loop In Javascript
The for loop is used to iterate through the characters of the string in reverse order. Starting from the last character (str.length – 1) and character pushed to the new reverse string one by one.
Example: The below code implements the for loop to reverse a string.
// Function to reverse string
function reverseString(str) {
let strRev = "";
for (let i = str.length - 1; i >= 0; i--) {
strRev += str[i];
}
console.log(strRev);
}
// Function call
reverseString("w3wiki");
reverseString("JavaScript");
reverseString("TypeScript");
Output
skeeGrofskeeG tpircSavaJ tpircSepyT
Reverse a String in JavaScript
We have given an input string and the task is to reverse the input string in JavaScript. It is a very common question asked in a JavaScript interview. There are various methods to reverse a string in JavaScript, which are described below with examples.
Examples:
Input: str = "w3wiki"
Output: "skeeGrofskeeG"
Input: str = "Hello"
Output: "olleH"