Hone logo
Hone
Problems

Reverse a String in JavaScript

This challenge asks you to write a JavaScript function that takes a string as input and returns a new string with the characters in reverse order. Reversing strings is a fundamental programming task and a good exercise for understanding string manipulation and basic algorithmic thinking.

Problem Description

You need to create a JavaScript function named reverseString that accepts a single argument: a string. The function should return a new string that is the reverse of the input string.

Key Requirements:

  • The function must return a new string. It should not modify the original string in place (strings in JavaScript are immutable, so this is naturally handled, but it's good practice to be aware of).
  • The order of characters in the returned string should be the exact opposite of the input string.

Expected Behavior:

  • If the input is "hello", the output should be "olleh".
  • If the input is "JavaScript", the output should be "tpircSavaJ".

Edge Cases to Consider:

  • An empty string ("").
  • A string with a single character (e.g., "a").
  • A string with spaces (e.g., "hello world").
  • A string with special characters or numbers.

Examples

Example 1:

Input: "hello"
Output: "olleh"
Explanation: The characters of "hello" are rearranged from last to first to form "olleh".

Example 2:

Input: "OpenAI"
Output: "IAnepO"
Explanation: The characters of "OpenAI" are reversed.

Example 3:

Input: ""
Output: ""
Explanation: Reversing an empty string results in an empty string.

Example 4:

Input: "a"
Output: "a"
Explanation: A single-character string reversed is itself.

Constraints

  • The input will always be a string.
  • The input string can be of any length, from 0 up to a reasonable limit (e.g., 1000 characters).
  • The function should be efficient.

Notes

There are several common ways to approach this problem in JavaScript. Consider methods like:

  • Using built-in string and array methods.
  • Iterating through the string manually.

Think about which approach might be the most concise and readable, and also consider the underlying mechanisms of how strings and arrays work in JavaScript.

Loading editor...
javascript