Longest word troubles

Longest word troubles
0

#1

Hello everyone. This code finds the longest word in a string and returns it as a number (or at least it supposed to). I can get it to pass all the test except when you pass in “May the force be with you”. var longest should return 5 and when I console.log longest, it shows 5. For some reason though I can’t get the code to pass the challenge, any idea what I did wrong?

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

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

#2

Global variables can cause problems with the tests if the variable which is global is the same variable being returned by the function. Why? Because the FCC test suite runs all of your code and then calls the function multiple times in a row. Each time the function is called, longest starts with the last value it had when the function was called. Try moving your declaration inside the function, so that each function call “resets” longest to 0.


#3

Thanks for your help once again!