Placement of a variable

Tell us what’s happening:
So my current code doesn’t prompt the “passed” screen when tested, but it spits back the correct numbers for all of the trials. I found that if I move my var arrayMax = 0; line just below the function line and above the var array = str.splt([" "]); line, it then passes the test. Why do i need to put the var arrrayMax = 0; inside of the function?

Your code so far

function findLongestWord(str) {
var array = str.split([" "]);
 
  for (var i=0;i < array.length; i++){
    //if new array word length is bigger than max, set it as new max length. otherwise, keep old one
    if (array[i].length > arrayMax){
      arrayMax=array[i].length;
    }
  
  }
  
  return arrayMax;
}

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/63.0.3239.132 Safari/537.36.

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

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