I have been working a javascript algorithm and have been confused why one works and the other one doesn't work. I have thought this through and I need a thorough explanation from many of you to hear different explanations to solidify my understanding of what is going on here.
Explain the difference between the two algorithms:
function findLongestWord(str) {
var longestNum = 0;
var splitStr = str.split(" ");
for(var i = 0; i < splitStr.length; i++) {
if(splitStr[i].length > longestNum) {
longestNum = splitStr[i].length;
}
}
return longestNum;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Why does the top one work and the bottom one NOT work?
function findLongestWord(str) {
var longestNum = 0;
var splitStr = str.split(" ").length;
for(var i = 0; i < splitStr; i++) {
if(splitStr[i].length > longestNum) {
longestNum = splitStr[i].length;
}
}
return longestNum;
}
findLongestWord("The quick brown fox jumped over the lazy dog");