Reverse a String in JavaScript

In this article, we will learn how to reverse a String in JavaScipt with an example.

Basically, we are going to learn different ways to reverse a String in JavaScipt.

Reverse String in JavaScript Example

Here are the three ways to reverse a String in JavaScript:

  1. With built-in functions
  2. With a for loop
  3. With recursion


Let's create a main.js file and add the following code to it:

// 1. With built-in functions

function reverseString(str) {
  return str.split('').reverse().join('');

console.log(reverseString("Source code examples"));

// 2. With a for loop

function reverseStringUsingLoop(str) {
  var newString = '';
  for (var i = str.length - 1; i >= 0; i--) {
      newString += str[i];
  return newString;

// 3. With recursion

function reverseStringusingRecursion(str) {
  return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);

Note that the comments in the above code are self-descriptive.


To test JavaScript code, let's create an HTML file named index.html and add the following code to it:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="main.js"></script>

Note that we have included the main.js file as an external JavaScript file:

<script src="main.js"></script>

Run index.html in Browser

Run above index.html file in browser and open dev tools -> console to see the output of the JavaScript code:

selpmaxe edoc ecruoS
selpmaxe edoc ecruoS
selpmaxe edoc ecruoS

Related JavaScript Examples