What's wrong with this function?

I’m trying to find the longest word in a string, and here’s my attempt.

function findLongestWordLength(str) {
  const words = str.split(" ")
  let longest = 0;

  for(let word in words){
    if(word.length > longest){
      longest = word.length;
    }
    return longest;
  }
}

it keeps returning 1, and I’m not sure what’s wrong with the function I wrote.

In this syntax of the for loop, “word” is not the element in the array, but the index of the element.

So to get the actual word value, you need to write: words[word]

Of course, I would rather name it something like “key” or “index”

1 Like

first of all, what do you want the function to return? You want it to return the length of the longest word? Or you want it to return the WORD? If you want to return the WORD, you need to have a variable for that too, such as longestWord and assign the word to it in a cycle.

Second, after using split you get an Array, not an Object, so you should use for(... of...) instead of for (... in ...) .

Hope this helps!

2 Likes

Interesting, I have never heard of “for of” and “for in” loops before this question. I have always used forEach for the same functionality, guess this is a better way.

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.