Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
reverse a string in Javascript using unshift function

Can anyone explain what's the mistake in the below code?

function reverseString(str) {
  let reversedStr = "";
  for (let i = 0; i < str.length; i++) {
    reversedStr.unshift(str[i]);
    return str;
  }
}
console.log(
 reverseString("hello")
 )

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You need an array to do unshift and the return outside the loop

const reverseString = str => {
  const rev = [];
  for (let i = 0; i < str.length; i++) rev.unshift(str[i])
  return rev.join("")
};
console.log(
  reverseString("hello")
)

but here is a oneliner

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

console.log(
  reverseString("hello")
)

about 4 years ago · Juan Pablo Isaza Report

0

Using unshift method

function reverseString(str) {
  let arr = [];
  for (let i = 0; i < str.length; i++) {
    arr.unshift(str[i]);
  }
  return arr.join("");
}
console.log(reverseString("hello"));

Alternative

If you meant to do the string reverse without using a util function, you can do it like below. If the string length is n then the time complexity of the below code is O(n/2).

function reverseString(str) {
  // get single characters into array
  const arrOfChars = str.split("");
  // get the half size of the array
  const halfLengthOfArr = Math.floor(arrOfChars.length / 2);
  // start index
  let i = 0;
  // swap chars until reach the middle of the array
  // h e l l o
  // ^       ^
  // o e l l h
  //   ^   ^
  // o l l e h
  while (i < halfLengthOfArr) {
    // swap coupterparts from start and end with same distance
    const start = arrOfChars[i];
    arrOfChars[i] = arrOfChars[arrOfChars.length - (i + 1)];
    arrOfChars[arrOfChars.length - (i + 1)] = start;
    i++;
  }
  // return the output array as a string
  return arrOfChars.join("");
}
console.log(reverseString("hello"));

about 4 years ago · Juan Pablo Isaza Report

0

I recommend completely going away from the unshift approach based on your requirement.

Therefore, I've designed two versions of your function for you and all are based purely on array functions.

Compact version:

function reverseString(str) {
    return str.split("").reverse().join("")
}

console.log(
    reverseString("hello")
)

Longer version (easier to understand):

function reverseString(str) {
    const characters = str.split("")
    const charactersReversed = characters.reverse()
    return charactersReversed.join("")
}

console.log( reverseString("hello") )

I hope that helped, even if I don't address your unshift request.

Last but not least, I've also reworked your initial code with your unshift function, even if I don't recommend this code in production:

function reverseString(str) {
    const reversedStr = [];
    for (let i = 0; i < str.length; i++) {
        reversedStr.unshift(str[i]);
    }
    return reversedStr.join("");
}

console.log(
   reverseString("hello")
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!