Troubles with a for loop

I am having trouble with the “Find the Longest Word in a String” challenge.
Basically - I have to find the longest word in the string and output the number of letters it has.
I am trying not to click the hint button as much as I can. I might be going in a completely wrong direction, but anyway…
This is what I imagined doing:
I wanted to split the given sentence into an array with words as values,and then I wanted to iterate through the array,take the iterated word and find its length,and at the end - use the sort function to sort it from the biggest to the lowest number.
After that - i would output the first (the biggest) value of the array. However - I am not understanding the way for loop works here… Check out the code I have written so far…

function findLongestWord(str) {
  var splitted = str.split(" ");
  for (var i = 0; i <= splitted.length; i++) {
  return splitted[i].length;
  return splitted;

The problem with the for loop I have is - I dont get all splitted[i].length that I expect. I only get my initialisation var i = 0;
returned. And what I wanted to happen is just have all my lengths returned in an array. This may not be the right way to solve this challenge,but I am very interested in how I could solve this problem I am having - I would love to know how to get all my .lenght values in an array , if that is possible...

Your line:

  return splitted[i].length;

will return only the first element in the spllited array, because as soon as you use the return statement, it sends any value after the return back to the calling function and does not come back (even if it was part of a loop that was not finished).

1 Like