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

198
Visualizações
Why does my for loop return 'undefined' as the last element of a string

I was trying to reverse a string using a for loop. The approach I took was to iterate backwards through the entire string, get each separate character of a string in a descending order and then concatenate the reversed characters together in a new, reversed string. However, I encountered a small issue - the string did reverse, but 'undefined' was concatenated at the start.

What am I doing wrong and why this is hapenning? Many thanks for help in advance.

Please, see the code snippet and console for details.

const string = "A quick brown fox jumped over the lazy dog.";
let newStr = "";

for (let i = string.length; i >= 0; i--) {
  let char = string[i];
  newStr += char;
}

console.log(newStr);

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because array starts from 0 and latest element is accessible by length-1 so the array[length] is equal to writing array[999999]

const string = "A quick brown fox jumped over the lazy dog.";
let newStr = "";

for (let i = string.length-1; i >= 0; i--) {
  let char = string[i];
  newStr += char;
}

console.log(newStr);
//alternative way
console.log(string.split('').reverse().join(''));

about 4 years ago · Juan Pablo Isaza Relatório

0

You should start from string.length - 1 since string[string.length] is trying to refer an element out of bounds of the array, hence, evaluates to undefined

const string = "A quick brown fox jumped over the lazy dog.";
let newStr = "";

for (let i = string.length - 1; i >= 0; i--) {
  let char = string[i];
  newStr += char;
}

console.log(newStr);

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