Basic Algorithm Scripting - Find the Longest Word in a String

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

I can get my code to pass all of the tests except for “May the force be with you”. When I console.log I get 5, which is the correct answer. Any idea why?

   **Your code so far**
//DECLARE VARIABLE FOR EMPTY ARRAY. TO BE USED TO CREATE WORD LENGTH ARRAY
let lengthArray =[ ];

function findLongestWordLength(str) {
 //SPLIT STRING UP INTO INDIVIDUAL WORDS
 str = str.split(' '); 
 
//ITERATE OVER ARRAY TO GET LENGTH OF EACH WORD
 for (let i= 0; i < str.length; i++){
   let length = str[i].length;
//ADD LENGTHS TO A NEW ARRAY   
   lengthArray.push(length)
 }
 //FIND MAX WORD LENGTH IN WORD LENGTH ARRAY
 let strLength = Math.max(...lengthArray)
 return strLength;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
   **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

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

Link to the challenge:

You are declaring lengthArray outside of the function which makes it a global variable. This is almost always a bad idea and it is in fact causing the test suite to fail. Always declare helper variables needed for the function inside the function.

1 Like

That did the trick. Thanks!

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