I m trying the following approach and I want to know why my inner loop is printing out undefine as seen in the screenshot. my thinking is when the first loop run, it will compare “The” string with every string in the nested loop and after “The”, it will compare “quick” with all the words inside the inner loop, but it seems like the out loop just run once with “The” and that is it.
What I am doing wrong?
function findLongestWordLength(str) {
//split the word where there is space
let words = str.split(" ")
//loop over each word length
for(let i = 0; i < words.length;i++){
//create a inner loop to loop over next sentence
console.log("i "+words[i])
//compare outer loop with inside loop
for(let x = 1; i < words.length; x++){
console.log("x "+words[x])
}
}
//reutn the largest one
return str.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
function findLongestWordLength(str) {
//split the word where there is space
let words = str.split(" ")
//loop over each word length
for(let i = 0; i < words.length;i++){
//create a inner loop to loop over next sentence
console.log("i "+words[i])
//compare outer loop with inside loop
for(let x = 1; i < words.length; x++){
console.log("x "+words[x])
}
}
//reutn the largest one
return str.length;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36
.
Challenge: Find the Longest Word in a String
Link to the challenge: