Problem with Find the Longest Word in a String using .sort() *SOLVED*

Hello fellow Campers!

I’m having a bit of a problem with the “Find the Longest Word in a String” challenge. The code below works as far as I can tell. I get a check mark for every criterion with the exception of “findLongestWord(“May the force be with you”) should return 5.” The problem is, when I pass that string in the console it does return 5. Is my code incorrect, or is this an error on the site itself? I’ve checked for typos, syntax errors, etc. and can’t find anything wrong. Does anyone else see where I’m messing up?

Thanks so much!


Your code so far

function findLongestWord(str) {
  var sentenceArr = str.split(" ");
  for (var i = 0; i < sentenceArr.length; i++) {
    wordLengths.sort(function(a,b) {
      return b - a;
  return wordLengths[0];

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

Your browser information:

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

Link to the challenge:

*** EDIT ***

for some reason, line 1 of my code didn’t pop up when I wrote the original post, so here it is, just to prevent confusion.

var wordLengths = [];

Thanks again!


You need to move that into the function. If not, since wordLengths is declared globally, each consecutive test will change the value of wordLengths and start with whatever elements were in wordLengths from the previous test. If you were to add the following line before the return statement, you would see how large the array is when it gets to the last test. Use the browser’s console (Ctrl+Shft+I in Chrome) to see what is happening. The FCC console is limited in what it can show.


By the time all the tests have completed, there are 58 elements in the array.

That did it! Thank you so much!

For anyone else that might see this post, randelldawson’s solution worked perfectly. After making wordLengths a local variable, I encountered no problems.

Happy Coding!