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

204
Visualizações
Why does this implementation of JavaScript to find the largest word return TypeError: Cannot read properties of undefined (reading 'length')

Why does the code below return the error? str is definitely a string so it is not undefined. words is an array so calling .length on it should also be valid. What is wrong with this implementation?

TypeError: Cannot read properties of undefined (reading 'length')

function findLongestWordLength(str) {
  let words = str.split(" ");
  let longword = words[0];
  for(let i = 0; words.length <= terminal; i++){
    if(words[i].length >= longword.length){
      longword = words[i]
    }
  }
  let longwordlength = longword.length;
  return longwordlength;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
// why is this giving the error: TypeError: Cannot read properties of undefined (reading 'length')
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your for loop condition is incorrect. It should be whether i is smaller than the number of words, since you are iterating through each word:

function findLongestWordLength(str) {
  let words = str.split(" ");
  let longword = words[0];
  for(let i = 0; i < words.length; i++){
    if(words[i].length >= longword.length){
      longword = words[i]
    }
  }
  let longwordlength = longword.length;
  return longwordlength;
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"))

However, a much more easier way to accomplish this task is to split the string by a space, map through the words and get each word's length, then use Math.max and spread syntax to get the biggest item:

function findLongestWordLength(str) {
  return Math.max(...str.split(" ").map(e => e.length))
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

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