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!!
let strArray;
let numArray = [];
function findLongestWordLength(str) {
strArray = str.split(' ');
for(let i = 0; i < strArray.length; i++){
numArray.push(strArray[i].length);
}
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
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?