Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda