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){
  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:

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

Like @ArielLeslie, your use of a global (outside of the function) variable arrayMax will start each test with the value it ended with in the previous test. This is why after findLongestWord(“May the force be with you”), the function returns 6 instead of 5. The previous test findLongestWord(“The quick brown fox jumped over the lazy dog”) resulted in maxArray being equal to 6, so since 6 is > 5, it still returns 6.