Tell us what’s happening:
hello, i need someone to explain some part of this algorithm for me.
maxlength was initialised as zero. Now according to the If () inside the for loop. it states that if arr[i] > maxLength which is zero. it should assign arr[i].length to maxlength. i dont see any reason why this algorithm should actually return the max length because every element of arr is greater than zero. I expect this alogorithm to either return all the length of arr[i] or add them together but not print out the highest. please explain why this code does work starting from the if statement. Thanks
Your code so far
js
function findLongestWordLength(str) {
var arr = str.split(' ');
var maxLength = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > maxLength) {
maxLength = arr[i].length;
}
}
return maxLength;
}
var result= findLongestWordLength("The quick brown fox jumped over the lazy dog");
console.log(result);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/