Correct answer not accepted - Find the Longest Word in a String

Tell us what’s happening:

My code passes all the other test cases, but fails “May the force be with you”.
The test case states it should return 5. I can see my code is in fact returning 5, but still fails the test.
Any help would be awesome!

Your code so far

var winner = 0;

function findLongestWord(str) {

  var arr = str.split(" ");
     for(var i = 0; i < arr.length; i++){
        if(arr[i].length > winner){
         winner = arr[i].length;
        }
     }
  
  return winner;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/find-the-longest-word-in-a-string

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums


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 new 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

Thanks! Makes sense.
I just found it confusing as the console was still outputting the correct answer.
But the local variable solution worked and passed all test cases :slight_smile: