JS CodeLab
algorithmsbeginner

JavaScript Reverse String Algorithm (split reverse join)

•
Updated

Direct Answer & Overview

Reversing a string in JavaScript is a core algorithmic problem. The standard idiom splits the string into an array of characters, invokes Array.prototype.reverse(), and joins the array elements back into a string with O(n) linear time complexity.

#algorithms#strings#reverse#interview-questions

JavaScript Source Code

example.js
function reverseString(value) {
  return value.split("").reverse().join("");
}

console.log(reverseString("JavaScript"));

How does this JavaScript code work?

Because JavaScript strings are immutable primitives, you cannot reverse characters in place. The idiomatic solution converts the string into an array using `value.split('')`, uses `Array.prototype.reverse()` to invert element order, and reconstructs a string using `join('')`. This runs in O(n) linear time and requires O(n) auxiliary space. For strings containing multi-byte Unicode surrogate pairs or emojis, using array spread `[...value].reverse().join('')` avoids splitting multi-byte characters.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
tpircSavaJ

Common mistakes to avoid

  • !Attempting to mutate string characters directly via index assignment (e.g. str[0] = 'a'), which fails silently in non-strict mode.
  • !Using value.split('') on strings with surrogate pairs or emojis, which splits surrogate code points and corrupts glyphs.
  • !Forgetting the empty string argument in join(''), which defaults to joining array items with commas (e.g. 't,p,i,r...').
  • !Using inefficient recursion for large strings, risking call stack overflow.

Frequently Asked Questions

What is the time complexity of reversing a string using split, reverse, join?

The time complexity is O(n), where n is the length of the string, because splitting, reversing, and joining each perform a single linear pass.

How do you reverse a string containing emojis or Unicode characters in JavaScript?

Use the array spread operator: [...str].reverse().join('') safely handles Unicode surrogate pairs and astral code points without splitting them.

Can you reverse a string without creating an array?

Yes. You can use a descending for-loop or while-loop, accumulating characters into a new string, or using two-pointer index traversal.