Find the Longest Word in a String [solved]

Tell us what’s happening:

ok. so this works. everywhere except on the page for the problem. (“May the force be with you”) returns 5 in VS Code + nodes.js console, online js compilers. but not here. frustrated!

Your code so far

function findLongestWord(str) {
  var arr = str.split(" ");
  var numArr = [];
  for (i = 0; i < arr.length; i++)
    console.log(arr[i].length + " = " + arr[i]);
  for (a = 0; a < arr.length; a++)
    if (numArr[a] > highest)
      highest = numArr[a];

  return highest;
findLongestWord("The quick brown fox jumped over the lazy dog");

Your browser information:

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

Link to the challenge:

Its not broken. highest is a global variable, so if you keep running the function with different inputs (which is what the tests do), it will retain the value of the last longest word. If you run it in isolation, just once, then it will give you the correct answer (which is why you can get it to work elsewhere).

I’m on a phone so can’t check this, but initialise it like var highest = 0 at the start of your function where you intialise the other two variables.

Note you’re also doing this in the loops, i and a are both global, though it doesn’t matter as much there.

1 Like


i moved highest into the top of the function and it passed on the site.


1 Like