How to reverse string in JavaScript using while loop

← PrevNext →

There are many ways you can reverse a string in JavaScript. I am sharing a simple method here, which shows how to reverse string or text in JavaScript using while loop. You can also use the for loop to reverse a string.

The method does not use any JavaScript built-in function to reverse a string. It uses a simple while loop.

<script>
  const s_word = 'JavaScript Program';
  let i = s_word.length;
  while (i--) {
   document.writeln(s_word[i]);
  }    //Output: m a r g o r P t p i r c S a v a J
</script>
Try it

This is one of oldest methods for reversing a text or string value. Its clean and does the job.

👉 More examples, and some different approach.

Reverse an Array using while loop

Although, we are talking about strings here, you can apply the above method on an array and reverse its values. For example,

<script>
  const s_word = ['JavaScript', 'Program'];   // its an array.
  let i = s_word.length;
  while (i--) {
   document.writeln(s_word[i]);
  }    //Output: Program JavaScript
</script>
Try it

The result however is different from the 1st example. Since its an array, its reverses the word, not the characters.

A More modern approach

Contrary to the above examples, especially the first example, this approach uses built-in functions, but it’s useful.

You can further simplify the above code using methods like reverse() and join(). I have previously shared a post explaining how to use the join() method in JavaScript. The example is very useful and I am sure you will like it.

So, using these method, we’ll first reverse the string and then join it again to the string.

<script>
  const s_word = 'JavaScript Program';
  const rev = [...s_word]
    .reverse()
    .join('');
  
  document.writeln(rev);   // Output: margorP tpircSavaJ;
</script>
Try it

In-addtion, you can use ES6 to make it a one-liner.

const rev = [...s_word].reverse().join('');

👉 See the three dots within the square brackets […]. It’s a Spread Operator. It splits the string. Check this out.

  const s_word = 'JavaScript Program';
  const rev = [...s_word];     // output: J,a,v,a,S,c,r,i,p,t, ,P,r,o,g,r,a,m

Thanks. 🙂

← PreviousNext →