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')
CodePudding user response:
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"));