0

# How this code returns maximum length of a string?

According to me it should return length of last word in a string(in the given example i.e, 7) ? Where I went wrong?Anybody clarify me https://code.sololearn.com/Wp33Vd4YLp30/?ref=app

23rd Jul 2020, 5:14 AM
Ajitha G R
+ 2
Martin Taylor Sry,I'm newbie ..But trying to understand... I know 8 is longer than 7 but I still thinking how this code inside the for loop returns 8 , I tried to understand but when i=0,it returns 4, i=1, //2 i=2,//3 i=3,//7 i=4,//8 . . i=9,//7 As far as I understood, irrespective of the longestword, it returns length of last word of the string.since I iterates till 9(index of last word) Which condition makes the function so it returns 8 ?
23rd Jul 2020, 6:58 AM
Ajitha G R
+ 1
Now I understood.,why did I make it complex ðŸ˜¬ðŸ˜‚.,thank you ðŸ™Œ
23rd Jul 2020, 9:04 AM
Ajitha G R
0
Martin Taylor function longestWord(str){ var words=str.split(' '); var maxLength=0; for(var i=0;i<words.length;i++){ if(words[i].length>maxLength){ maxLength=words[i].length;/*returns first word , i increments to 1,returns 2nd word.so on*/ } } console.log(maxLength); } longestWord("What is the average airspeed velocity of an unladen swallow");
23rd Jul 2020, 5:42 AM
Ajitha G R
23rd Jul 2020, 5:54 AM
Ajitha G R