Function passes 4/5 challenges and should pass the 5th?

Tell us what’s happening:
The function takes a sentence (string) and finds the longest word. It passes for 4 of the 5 test cases. But if you pass it “May the force be with you” it counts “force” as 6 characters not 5.

The array it creates is correct [‘force’], so I can’t work out how it’s counting 6.

Any ideas?

Your code so far


let longestWord = 0
function findLongestWordLength(str) {
const regex = /\w*\S/g;
let array = str.match(regex);
console.log(array)

for (var i = 0; i < array.length; i++) {
  if (array[i].length > longestWord){
    longestWord = array[i].length;
  }
} 
console.log(longestWord);
return longestWord;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");

/// its findin 6 letters in 'force'....//


Your browser information:

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

Challenge: 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 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.

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

Ahh, i see!

Thanks ArielLeslie (totally not a bot ) :slight_smile:

Fixed code here just in case anyone else falls fowl to variable scope

// let longestWord = 0 // bad global variable

function findLongestWordLength(str) {

    let longestWord = 0 //Good local variable

    const regex = /\w*\S/gi;

    let array = str.match(regex);

    console.log(array)

    for (var i = 0; i < array.length; i++) {

      if (array[i].length > longestWord){

        longestWord = array[i].length;

      }

    } 

    console.log(longestWord);

    return longestWord;

}

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

Congratulations on solving the challenge! I’ve added spoiler tags to your reply so people only see your solution if they want to. :smiley: