# Find the Longest Word in a String.?

I’m stuck in part and Maybe I’m missing something or I’m totally wrong but I can’t figure out what is wrong in my syntax.Can you help me?

function findLongestWord(str) {

var a = str.split(" ");
var y = [];
y.push(a);
var con = “”;

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

`````` if(y[i].length>y[i+1].length){
con = y[i];
``````

}

``````else if(y[i].length<y[i+1].length){
con = y[i+1];
}

else if(y[i].length>y[i-1].length){

con = y[i];

}
else if(y[i-1].length>y[i].length){

con = y[i-1];

}
else {

con = y[i];

}
``````

}
return con.length;
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

First of all, your 2nd and 3rd lines `y.push(a);` and `y.push(a);` are redundant; you’re basically taking the empty array `y` and pushing all of array `a` onto it. Just use your array `a`.

Secondly, you’ve got way too many else statements which is super confusing.
Here’s my solution, which is probably not ideal, but works on the same principles as yours, with much more brevity:

My solution:
``````function findLongestWord(str) {

var strArray = str.split(" ");
var newLength = 0;
var eachWord;

for ( var i = 0; i < strArray.length; i ++ ) {
eachWord = strArray[i].length;
if ( eachWord > newLength ) {
newLength = eachWord;
}
}

return newLength;
}

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

Also, may I recommend you use some spacing in your code - it’s hard to read.
For example:

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

if ( y[i].length > y[i+1].length ) {

etc...
``````