Longest Word Problem?

Tell us what’s happening:

Why doesn’t my code pass the tests? cording to the console.log(longest), my variable “longest” is set to a value of 5 after going through the function for the below example>

Your code so far


function findLongestWordLength(str) {
var longest = 0
var strArr = str.split(' ');
for (i = 0; i < strArr.length; i++) {
  if (strArr[i].length > longest) {
    longest = strArr[i].length
  }
}
console.log(longest);
return longest;
}

findLongestWordLength("May the force be with you");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36.

Challenge: Find the Longest Word in a String

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

You need to declare i in the for loop with let or var.

1 Like

If there is no strict mode, this is not a problem in JavaScript.

I think the FCC tests are run in strict mode.

I just tried it by declaring i in the for loop and it passed. I do believe that @stressstressstress is correct about the test being ran in strict mode.