Here's some code found "in the wild" that runs without errors. What does it do?

1 const longestWord = Math.max(_.map(label.split(), w => w.length)) // label is a string of "normal" english text
2 // _.map(foo, func) is like foo.map(func)


If you are anything like me, you don't actually have the exact details of common functions memorized, so your thought process when reading this code is probably something like:

"label.split() splits up the string somehow, then the map returns the length of each element that was split up, so I can assume then that .split() splits on whitespace by default, and Math.max() can accept an array of numbers as input."

Wroooong.

Here's what actually happens:

1 const label = "Im a words!"
2 const splitLabel = label.split() // ["Im a words!"]
3 const mappedLabel = _.map(splitLabel, w => w.length) // [11]
4 const longestWord = Math.max(mappedLabel) // 11

Without arguments, .split() doesn't split on anything. It just puts the whole string inside a single-element array. Let's fix that:

1 const label = "Im a words!"
2 const splitLabel = label.split(" ") // ["Im", "a", "words!"]
3 const mappedLabel = _.map(splitLabel, w => w.length) // [2, 1, 6]
4 const longestWord = Math.max(mappedLabel) // NaN

Notice that now, splitLabel and mappedLabel give the expected results, but the max() operation returns NaN. This is because Math.max() does not actually accept arrays. For some reason that I do not know, it does allow a length 1 array, but longer arrays are not accepted. The input has to be "spread", e.g. Math.max(2, 1, 6)

The correct code is:
1 const wordLengths = _.map(label.split(" "), w => w.length) // [2,1,6] using split(" ")
2 const longestWord = Math.max(...wordLengths) // 6 use spread operator to pass array in

So I know what you're thinking now. "David, what does ANY of this have to do with types, type checking, or JSDOC?".

I'm glad you asked. The point of this long-winded example is that programming can be tricky. In Python, the original code would have worked fine. string.split() does split on whitespace, and max() does accept arrays. And, if you think this example has nothing to do with types, then I'm glad you are seeing it, because here is what the original code looks like with a type checker turned on:

back