Hello I tryed converting a string to array and then finding the biggest word, output should be length of the word in numbers. Im not sure what im doing wrong and why this code is not working if someone could point it out for me I would be very grateful.
function findLongestWordLength(str) {
let words=str.split(" ");
let bigword=0;
for(let i=0; i<=words.length; i++) {
if(words[i].length>bigword) {
bigword=words[i].length;
}
}
return bigword;
}
5
Answers
In your for loop, you are iterating a bit far away.
You can replace
i<= words.length
byi< words.length
It’s because your loop runs longer than there is elements in array.
Change
i<=words.length
toi<words.length
You can also use
Math.max
with passed mapped array of words lengths: