reverse a string in javascript without using any array methods in javascript

To reverse a string in JavaScript without using any array methods, we can use a loop to iterate over each character of the string from the end to the start, and concatenate each character to a new string.

Here's a code snippet that demonstrates this approach:

index.tsx
function reverseString(str) {
  let reversedStr = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversedStr += str[i];
  }
  return reversedStr;
}

// Example usage:
console.log(reverseString('hello')); // Output: 'olleh'
230 chars
11 lines

In this code, we declare a new string variable called reversedStr, initialize it to an empty string, and then use a for loop to iterate over each character of the input string str, starting from the end (i.e. the index of the last character is str.length - 1) and moving towards the start (i.e. index 0).

Inside the loop, we concatenate each character of str to the reversedStr variable, using the += operator. This creates a new string that has the same characters as str, but in reverse order.

Finally, we return the reversedStr string from the function.

This method of reversing a string is an example of a common string manipulation technique that involves iterating over a string and building a new string one character at a time. It is a good example of how to use loops and string concatenation in JavaScript.

gistlibby LogSnag