# Find the Longest Word in a String-Thanks in advance!

Tell us what’s happening:
Anyone can help to fix my code? My logic is wrong?

``````
function findLongestWordLength(str) {
let count = 0;
let length = [];
for (let i = 0; i < str.length; i++) {
if (str[i]>="a" && str[i]<="z" || str[i]>="A" && str[i]<="Z") {
count++;
}
else {
length.push(count);
count = 0;
}
}
return Math.max(length);
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36`.

To find the longest word in the array first convert this string in an array

``````var largestWord=0

var logestWordinArry=["The"," quick", "brown"," fox", "jumped", "over", "the"," lazy", "dog"]
then you have to iterate through the array

largesWordinArry[0].length
largesWordinArry[1].length
largesWordinArry[3].length
largesWordinArry[4].length
use for loop.
to splits sentence into the collection words stored in array, you can use split(' ')
now it is exactly like how you find largest number in array
``````
``````var sentence='John is going'

for(var i=0;i<name.length;i++){

console.log(sentence[i])
value of i                  and result
0                                J
1                               o
2                               h
3                                n
4                                   space
5                                    i
6                                       s
continue the process
what i mean to say that if you don't split that sentence into the collection of word stored in array, it can only iterate though each letter

}
``````

Your logic is very low level but correct nonetheless, it’s this part that’s messing with your code:

`return Math.max(length);`

The max method does not take an array as argument, but one or more arguments and then returns the maximum number out of the argument list passed to it:

``````Math.max([1,2,3]) // NaN
Math.max(1,2,3) // 3
``````

Thankfully there’s a way to make `Math.max` consume your array as if it were separate arguments:

``````// The old way with Function.prototype.apply
Math.max.apply(null, [1,2,3]) // 3

// The new, ES6 way with the 'spread operator'
Math.max(...[1,2,3]) // 3
``````

For `apply` reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
It falls under the same discussion as saying using `Array.filter()` is better than doing the for loop and if statement yourself. It may be some micro/milliseconds faster but if you already have a generic version inside the language then you may as well use it.