2 ms·
Exactly, and the article's example is spot on for how these expectations get violated by CS's behavior. In CS, the assumption is that aside from minor (and easy
by mistercow 14y ago
Exactly, and the article's example is spot on for how these expectations get violated by CS's behavior. In CS, the assumption is that aside from minor (and easy to detect) performance penalties, returning a nonsensical value from a function is harmless.
But libraries like jQuery actually give meaning to "no return" in some callbacks. They cleverly let that be the most common behavior, and then let return values specify less common behavior. An example of this in jQuery that creates even more aggravating bugs is event handling. Here's a simple example: http://jsfiddle.net/63fUY/ http://jsfiddle.net/63fUY/ .
The expectation is that each time you click either button, the total count will increase. But because of the implicit return on line 13, preventDefault gets called half the time. That's an incredibly easy mistake to make, a huge pain to hunt down, and awkward to write a test for. And it would be so easy to avoid if the language had a syntax for "default to no return" which we could just use on all event handlers.
- masklinn 14y ago> Here's a simple example: http://jsfiddle.net/63fUY/ http://jsfiddle.net/63fUY/ . Hah. Fun one. > And it would be so easy to avoid if the language had a syntax for "default to no return" which we could just use on all event handlers. Alternatively, rollback the "implicit return" but make the explicit return short and sweet yet still visible. E.g. use Smalltalk's unary `^` (which as far as I know currently exists neither in JS nor in CS) so the callbacks would be: -> totalClicks++ $('#total').text totalClicks ^false # explicitly return false and -> $('#state').text if nextState then "On" else "Off" nextState = !nextState # no explicit return -> undefined as in JS