How to reverse a string in JavaScript?

Asked by Mike Johnson Jul 22, 2025 beginner 1642 views
89

I need to reverse a string in JavaScript. For example, "hello" should become "olleh".

I've tried using a for loop but my code isn't working:

function reverseString(str) {
  let reversed = "";
  for (let i = str.length; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}

What am I doing wrong? Also, is there a more elegant way to do this in modern JavaScript?

Solutions

2 answers
Accepted Answer
156

Great question! There are several ways to reverse a string in JavaScript. Let me show you:

Method 1: Using built-in methods (Most common)

function reverseString(str) {
  return str.split('').reverse().join('');
}

console.log(reverseString("hello")); // "olleh"

How it works:

  1. split('') - converts string to array of characters
  2. reverse() - reverses the array
  3. join('') - joins array back to string

Method 2: Using a for loop (Your approach, fixed)

function reverseString(str) {
  let reversed = "";
  for (let i = str.length - 1; i >= 0; i--) {  // Start at length - 1!
    reversed += str[i];
  }
  return reversed;
}

The bug in your code: you started at str.length but should start at str.length - 1 because array indices are 0-based.

Method 3: Using reduce (Functional approach)

function reverseString(str) {
  return [...str].reduce((rev, char) => char + rev, '');
}

Method 4: Using recursion

function reverseString(str) {
  if (str === "") return "";
  return reverseString(str.substr(1)) + str[0];
}

Performance Tip: For very long strings, the for loop method is fastest because it avoids creating intermediate arrays.

Hope this helps!

Answered by Sarah Chen Dec 5, 2025
89

The built-in method is great for most cases, but if you're in a coding interview, they might ask you to do it without built-ins:

function reverseString(str) {
  const chars = [...str];
  let left = 0;
  let right = chars.length - 1;

  while (left < right) {
    // Swap characters
    [chars[left], chars[right]] = [chars[right], chars[left]];
    left++;
    right--;
  }

  return chars.join('');
}

This is O(n) time and O(n) space (O(1) extra space if you can modify in place).

Answered by Tom Harris Jan 6, 2026