TL;DR
Your numbers are getting sorted as strings.
To get them sorted as numbers, in descending order, in your function you should instead do:
wordArray.sort(function(a, b) { return b - a; });
EXPLANATION
According to the docs:
The sort() method sorts the elements of an array in place and returns
the array. The sort is not necessarily stable. The default sort
order is according to string Unicode code points.
[...]
Syntax
arr.sort()
arr.sort(compareFunction)
Parameters
compareFunction
Optional
Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point
value, according to the string conversion of each element.
Emphasis mine, so you end up with something like this:
var str = "What if we try a super-long word such as otorhinolaryngology";
var charArray = str.split(" ");
// now charArray == ["What", "if", "we", "try", "a", "super-long", "word", "such", "as", "otorhinolaryngology"]
// when you take the length of each word and end up with
var wordArray = [4, 2, 2, 3, 1, 10, 4, 4, 2, 19];
// and if you use plain wordArray.sort() without specific sort function you get
wordArray = [1, 10, 19, 2, 2, 2, 3, 4, 4, 4];
// and once reversed it is
wordArray = [4, 4, 4, 3, 2, 2, 2, 19, 10, 1];
// this is why you end up with wordArray[0] == 4
You could also implement the whole function as a one-liner:
function findLongestWord(str) {
return str.split(/\s+/).sort(function(a, b) { return b.length - a.length; })[0].length;
}
console.log("Longest word length = ", findLongestWord("The default sort order is according to string Unicode code points"));
console.log("Longest word length = ", findLongestWord("What if we try a super-long word such as otorhinolaryngology"));