My function is behaving oddly, requires a comment out to solve consistently - Find the Longest Word in a String

So my solution seems to work but only when I comment out the actual function call

Your code so far

let myRegex = /\w+/gi;
let emptyArr= [];
let upCounter = 0;

function findLongestWordLength(str) {
let result = str.match(myRegex);
for (let i=0; i<= result.length -1; i++){



    for (let j=0; j < emptyArr.length; j++) {

      if (upCounter < emptyArr[j]){

        upCounter = emptyArr[j];



    return upCounter;   


findLongestWordLength("The quick brown fox jumped over the lazy dog");

My issue is that it only clears me when i comment out the pre-installed function call as such

//findLongestWordLength("The quick brown fox jumped over the lazy dog");

Otherwise it throws me a fail on condition three - longest word in "May the Force be With you" (max length 5)

i suspect my upCounter is not resetting between the first test case (leaving it at 6)
and refusing to accept the second case, since the inbuild function call is already at 6. Does the upCounter =0; just need to be placed somewhere else? i've tried to move it around to re-initialize it between runs, but it dosen't seem to work out for me.

Your browser information:

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

Challenge: Find the Longest Word in a String

Link to the challenge:

Hint: do some googling around for problems caused by the g flag.

uh I think your issue is an other instead

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 previous 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
1 Like

That makes alot of sense thank you