Burning the Loop at Both Ends

June 26, 2020

This may not be the most earth-shattering coding tip, but it’s pretty interesting and has helped me in interviews… and let’s be honest, as a front-end developer interviews are half the battle.

One of the most frequently asked interview questions I’ve encountered (right after “what’s the difference between == and === ?”) is this little gem:

Q. “Write a function to reverse a string…”

No Problem. BAM! Here you go:

const reverseString = str => [...str].reverse().join("");

…without using Array.prototype.reverse()

Ah ok.

There are probably a dozen or so solutions to this one, but a simple approach is to iterate over each letter in a string (remember that strings are iterable), prepending each letter to a new array, then join('') the array to create a new string:

const reverse = str => {
  const result = [];

  for (let i = 0; i <= str.length; i = i + 1) {
  return result.join("");

reverse("Yo, banana boy!"); // => "!yob ananab ,oY"

Looks good, but what if we could speed things up a bit by running our loop in half the time? In the below sample we iterate over half of the length of the string (str.length / 2) and build a new array by appending and prepending characters in the same iteration.

function reverseFromBothEnds(str) {
  const result = [];

  for (let i = 0; i < str.length / 2; i = i + 1) {
    let positionStart = i;
    let positionEnd = str.length - 1 - i;

    result[positionStart] = str[positionEnd];
    result[positionEnd] = str[positionStart];

  return result.join("");

reverseFromBothEnds("Never odd or even"); // => "neve ro ddo reveN"

So keep in mind, you can use this approach for a lot of different coding challenges that involve iterating through a collection with a for loop.

Happy Coding!

Mark Barry - Front-end Developer
Orange County, CA.

© 2021