JavaScript: Reverse a String

1. Introduction

Reversing a string is a classic programming task that is often used as a demonstration of string manipulation techniques in various languages. In this post, we'll explore a simple yet efficient way to reverse a string using JavaScript.

2. Program Overview

In this guide, we will:

1. Begin with a sample string.

2. Implement a function to reverse the string.

3. Display the reversed string.

3. Code Program

let originalString = "JavaScript";  // String to be reversed
let reversedString = "";  // Variable to store the reversed string

// Function to reverse a string
function reverseString(str) {
    return str.split('').reverse().join('');

reversedString = reverseString(originalString);

console.log("Original String: " + originalString);
console.log("Reversed String: " + reversedString);


Original String: JavaScript
Reversed String: tpircSavaJ

4. Step By Step Explanation

1. Variable Initialization: We define our originalString which we want to reverse, and a variable reversedString which will store the result.

2. String Reversal Function: The reverseString(str) function accomplishes the reversal in three primary steps:

  • split(''): This method splits the string into an array of its characters.
  • reverse(): This array method reverses the order of elements in an array.
  • join(''): Joins the array elements back together into a single string.

3. Function Invocation: We then call the reverseString function with our original string and assign the result to reversedString.

4. Displaying Results: Using the console.log method, we showcase both the original and reversed strings, providing a clear before-and-after perspective.