🟨 JavaScript
Easy
🕐 6 min

String Reversal Function: reverseString

Goal: create a function reverseString(str) that returns the input string reversed.

💡 Solution hint:

Possible solutions:

  1. Use split(''), reverse(), join('')
  2. Use a for‑loop iterating backwards
  3. Use recursion (base case: empty string)

Example with array methods:

function reverseString(str) {
  return str.split('').reverse().join('');
}
👀 Peek at solution #1 (Array methods):
/**
 * Reverses a string by changing the order of characters
 * @param {string} str - The input string to reverse
 * @returns {string} The reversed string
 */
function reverseString(str) {
  // 1. Split the string into an array of individual characters
  //    Example: "hello" -> ["h", "e", "l", "l", "o"]
  // 2. Reverse the order of array elements
  //    ["h", "e", "l", "l", "o"] -> ["o", "l", "l", "e", "h"]
  // 3. Join the reversed array back into a string
  //    ["o", "l", "l", "e", "h"] -> "olleh"
  return str.split('').reverse().join('');
}
window.reverseString = reverseString;

Why this way:

  1. Uses built‑in JavaScript methods, short and readable.
  2. Time complexity O(n), space complexity O(n).
  3. Works for any string, including with spaces and Unicode.
👀 Peek at solution #2 (Loop):
function reverseString(str) {
  let reversed = '';
  for (let i = str.length - 1; i >= 0; i--) {
    reversed += str[i];
  }
  return reversed;
}
👀 Peek at solution #3 (Recursion):
function reverseString(str) {
  if (str === '') return '';
  return reverseString(str.slice(1)) + str[0];
}

Task description

Create a function reverseString that takes a string and returns a new string with the characters in reverse order.

How the function should work:

  1. Takes one parameter — a string
  2. Returns a new string with characters in reverse order
  3. Should work correctly with empty strings and palindromes

Usage examples:

reverseString('hello'); // 'olleh'
reverseString('a b'); // 'b a'
reverseString('madam'); // 'madam'

Requirements:

  • The function must be named reverseString
  • Accepts one string argument
  • Returns the string reversed
  • Must not modify the original string
  • Must handle Unicode and spaces

🧑‍💻 It's not a bug! It's a feature!

The code editor is intentionally hidden on mobile.

Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.

📖 Now: Study the task, think through the solution. Act like a strategist.

💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!