Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda