DEV Community

Discussion on: How to Reverse a String in JavaScript

Collapse
 
sebvercammen profile image
Sébastien Vercammen • Edited

The reverse of a string, is that string traversed in reverse order.

Sounds obvious, but this is more efficient in languages that let you work with memory directly (swap a string's characters in place, or write the string to an output buffer in reverse).

Reasonable answers include their use cases and performance characteristics.

  • Benchmark for short strings
  • Benchmark for long strings
  • In use cases where the entire text doesn't need to be reversed at once (e.g. consuming the stream in real-time is more important than the fully reversed output), you may prefer to write a method that lazily yields letter by letter. It will have a slight overhead cost for each function call, but that's completely voided by the needs of your use case.

The recursive examples present a different problem: Most implementations don't support tail call optimization, so you might run into the upper limit of your call stack.

Everything also depends on JS implementation (e.g. different browsers). You may get different, maybe even opposite, results.

PS: These answers are valid today, but they might not be in the future. I've seen browser implementations change so often that the results jump from patch to patch. Don't expect anything in this thread to be a final answer, and instead learn to explain yourself and your thinking.