In this tutorial, you’ll learn a couple of ways to reverse a string in JavaScript. You’ll learn how to reverse a string using reduce, reduceRight, reverse method and simple for loop.

Using Reduce() Method

You can use reduce method to reverse string in JavaScript. Here is how you can use it:

function reverse(str){
  let arr = str.split('');
  return arr.reduce((accumulator, currentValue) => {
    return currentValue + accumulator
  })
}

console.log(reverse("abc"))

Using ReduceRight() Method

The difference between reduce and reduceRight method is that it iterates from right to left. You can use it to reverse string in JavaScript. Here is how to use it:

function reverse(str){
  let arr = str.split('');
  return arr.reduceRight((accumulator, currentValue) => {
    return accumulator + currentValue
  })
}

console.log(reverse("abc"))

Using For Loop

A simple for loop can be used to reverse a string in JavaScript. You can iterate through the string elements from right to left, store it in an array and convert array to string it to reverse the string. Here is how the code looks:

function reverse(str){
  let arr = str.split('');
  let tmp = [];
  for(let i = arr.length; i > -1; i--){
    tmp.push(arr[i])
  }
  return tmp.join('')
}

console.log(reverse("abcdef"))

Using Reverse Method

JavaScript Array has a built in method called reverse to reverse an array. You’ll first convert the string to array and then use the reverse method to reverse it. Here is how the code looks:

function reverse(str){
  let arr = str.split('');
  return arr.reverse().join('');
}

console.log(reverse("abcdef"))

Wrapping It Up

In this tutorial, you learnt about a couple of ways to reverse a string in JavaScript. You learnt how to reverse a string using for loop, reduce, reduceRight and reverse method.

If you know of any other method to reverse a string in JavaScript, do let us know in the comments below.