# Possible Exercise Glitch - Find the Longest Word in a String

Possible Exercise Glitch - Find the Longest Word in a String
0

#1

Tell us what’s happening:
I think there must be a glitch with this exercise; it will take all the test cases except one. I believe I have the correct answer, but it gives me the error message, "findLongestWord(“May the force be with you”) should return 5. ". In fact, changing the test text to “May the force be with you” returns 5. What am I missing? I reviewed other posts on this subject and did not notice anybody else experiencing the same thing.

~Jessiah

``````var newArray = [0];

function findLongestWord(str) {
array = str.split(' ');
for (i = 0; i < array.length; i++) {
newArray.push(array[i].length);
}
newArray.sort(function(a, b) {
return a - b;
});
return newArray[newArray.length - 1];
}

findLongestWord("May the force be with you");
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0`.

#2

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
``````