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:

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.


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.


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

function returnLocal(arg) {
  var myLocal = [1];
  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: