My very wel written, (hahaha... ) code doesn't work how it should

I have written this piece of code for the “Basic Algorithm Scripting: Find the Longest Word in a String” - assignment. It works on all but one of the tests. It does pass the test, if I try it in my own editor.
I can’t seem to figure out what is wrong, please help!! :slight_smile:

let strArray;
let numArray = [];

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

findLongestWordLength("May the force be with you");

Global variables. After the first test you’ll have the word lengths of the first sentence in numArray, then you’ll have the word lengths of the first + second sentence and so on

Thank you so much!

Putting let numArray = []; inside the function, makes it work fine.

I still don’t understand why it did work with all the other sentences, just not with “May the force be with you”. Do you maybe have an explanation for that?

Oh, I get it!
All the tested sentences are added to the numArray, and with every new test it does not reset, but adds the next sentences’ numbers.

Thank you for having taken the time to answer and explain!

1 Like