← Back to libraryQuestion 150 of 468
🧩JavaScript CodingBeginner

Reverse a String

📌 Definition:

Return a string with its characters in reverse order (e.g. "hello" -> "olleh").

📖 Detailed Explanation:

Strings are immutable in JavaScript, so you build a new value. The idiomatic one-liner splits into an array of characters, reverses the array, and joins back. A manual loop from the last index is also O(n).

💻 Solutions:
function reverseString(s) {
  return s.split('').reverse().join('');
}
// Unicode-safe version (handles emoji/surrogate pairs):
const reverseUnicode = (s) => [...s].reverse().join('');
🔑 Key Points:
  • split('').reverse().join('') is the classic idiom
  • [...s] spread is Unicode-safe for emoji/surrogate pairs
  • Strings are immutable — you return a new string
  • O(n) time
🌍 Real-World Example:

Reversing strings underpins palindrome checks and building deterministic cache keys; as an interview opener it checks whether you know JS string/array methods.

🎯 Scenario-Based Interview Question:

Your reverseString('👍a') returns garbled output. Why, and how do you fix it?