Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
Describe your issue in detail here.
I solved the challenge in another method. But i would like to know why this code doesn’t work. The elements of words list is not being passed to word variable in for loop but i don’t know why?

Your code so far

function findLongestWordLength(str) {
  
  let words = str.match(/\w+/ig);
  //console.log(words)
  let longestWord = "";
  for (let word in words) {
    console.log(word)
    if (word.length > longestWord.length) {
      longestWord = word;
    }
  }
  console.log(longestWord.length)
  return longestWord.length;
  
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.54

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

Hello,

Your for...in loop is the culprit here. For...in is used to iterate of the properties of an object. For...of is used for arrays.

This article talks a bit about what is going on behind the scenes when you called for...in on an array object.

Thanks for the quick reply. Now, it makes sence.

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