Longest Word Activity - Stuck

Tell us what’s happening:

I’ve written a script that I think should work but clearly doesn’t. I’m just not sure what’s broken about it. I’ve tried to console.log() various sections and they log what I expect them to. It seems like my for loop isn’t incrementing and looping, but I’m not sure. Any kind of hint or link to a resource would be helpful. Am I even able to solve it using the for loop and if statement?

Thanks

Your code so far



let currentWord = "";
function findLongestWordLength(str) {
let splitStr = str.split(" ");
for (let i = 0; i < splitStr.length; i++) {
   if (splitStr[i].length >= currentWord) {
      currentWord = splitStr[i];
    } 
}
return currentWord.length;

}

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

Your browser information:

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

Challenge: Find the Longest Word in a String

Link to the challenge:

In the if condition you need to make this change. You need to compare length of the both variables.

Change this splitStr[i].length >= currentWord to splitStr[i].length >= currentWord.length.

if (splitStr[i].length >= currentWord.length) {
      currentWord = splitStr[i];
}
1 Like

my god lol. Thank you. I was googling about if statements nested in for loops trying to figure out if I had messed up there when all it was is I forgot .length.

Thanks!

1 Like

My pleasure. I’m glad I could help you buddy :heart:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2