Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Discover Mentorship
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Home/Pills/ Pill - Reverse String in JavaScript/
Home/Pills/Pill - Reverse String in Ja.../
Image by zhugewala from Pexels

Reverse String in JavaScript

Feb 2, 2021

DESCRIPTION

There is no-built in method on string type to reverse it in JavaScript, let's see how we can overcome it with a one-liner solution.

Preview

reverseString one-liner

JavaScript

Summary

  • We created reverseString function which accepts a string argument.
  • Using Rest spread operator and array syntax, we're spreading letters of string into array, e.g. "abc" -> ["a", "b", "c"].
  • Then, we're calling .reverse() built-in array method (it doesn't exist on string type 😭), ["a", "b", "c"] -> ["c", "b", "a"].
  • After that we're combining array items (letters) using .join() array method with "" argument to avoid commas into our final reversed string, ["c", "b", "a"] -> "cba".
  • It's a nice one-liner code but not the fastest one, here you can read about more solutions to this problem.
  • I still chose the one-liner solution as it looks clean - declarative code is more important than the performant one unless performance really hits. 😅
THE GUIDE TO BEAT FRONTEND INTERVIEW
From time to time, I'll send you messages about new blog posts, knowledge pills, and mentoring promotions. Only valuable information, no spam included. You can unsubscribe at any time.
slack
Let's build a community that will help each other.
spread the word
You don't need to, it's okay...