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

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

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 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