Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!