Find the Longest Word in a String - Math.max issues!

Hello everyone!

There are other post on this exercise but i want to see what was flawed in my logic.

One thing that is throwing me off is when i run the “largest” variable with “test” it works fine. But when i run it on “count” it returns null. But when i return just “count” an array of numbers appears.

function findLongestWord(str) {
  var normal = str.split(' ');    // split str into an array
  var count = [];    // an empty array to store values
  var test = [1,2,3];    
  var largest = Math.max.apply(Math, count);   // works with test but not count
   
 for(var i = 0; i < normal.length;i++){
   count.push(normal[i].length);
 }
  return largest ;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

Your function returns -Infinity when I run it. According to the documentation

If no arguments are given, the result is -Infinity.

Passing an empty array to Math.max.apply is the same as passing 0 arguments. Not sure how you got null.

You should fill count before call for Math method, otherwise it has a -Infinity result.
So, your for is in late in this flow of code, it should come first :slight_smile:

EDIT: Even if you fill count first, be careful on what you return: you will call the Math method on an array with the length of the original words in it. Is the length of the largest word what you have told to return?

So close.

A. Correct to: var largest = Math.max.apply(null, count);

B. This line should be used after the loop because count is still []