Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
Describe your issue in detail here.

I’m not sure what’s going on here? This function seems to work properly but for some reason on the third test that is testing “may the force be with you” it returns 6 instead of 5? It works for all the others. I even added “elephant” to the string, and it returned 8.

Any idea what is going on here?

Your code so far

let numberArray = []

function findLongestWordLength(str) {
  str = str.split(' ')
    for (let i=0; i < str.length; i++) {
      str = Math.max.apply(Math, numberArray)
      return str;

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

Your browser information:

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

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each function call completes, subsequent function calls 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

This is a bad variable name here.

Thanks for the quick response, I’m going to try and fix it up.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.