The Wun Show: Douglas Crockford has been sniffing JavaScript's bad parts again

The Good, the Bad, and the Wunderful

Stob In the opening chapter of his latest book How JavaScript Works (pub. Virgule-Solidus, 2018, c. £24.19, pp 279), Douglas Crockford introduces us to a selection of English linguistic idiosyncrasies that he will inflict on his readers.

The most startling of these is his spelling of "one" – yes, yes that Kelly's eye, that ineffectual multiplier, that name Prince Charles calls himself – which he, Crockford, insists on rendering "wun". Over and over again. With all the adorable variations tossed in for free: somewun, anywun, no wun, I wunce wrote a constructor, wunth and, brace yourself for it, twoth.

This is quite annoying and distracting, but no more so than an economy-class, transatlantic flight in a cramped, middle-aisle seat in front of a poorly disciplined ADD boy-child whose seatback kicks are Poisson-distributed with Lambda around 4.7 per minute.

I am sure I have seen that spelling "wun" before, in the writings of Daisy Ashford, Alan Alexander Milne, or some other whimso children's author. We have waved "buh-bye" to the wild worldwide web. We have touched down in the Wun Hundred Acre Wood.

Good parts

Given this finitely promising start, non-JavaScript-oriented Reg readers might reasonably wonder why we are here at all.

The reason is historic. At the turn of the millennium, the Programming High Command treated JavaScript as a toy language, fit only for fumbling the mouse-over event of hideous web pages, and for patronising ripostes: "No, no – you are confusing it with Java. It's nothing to do with Java! You fell for the marketing! Har, har, har."

But Douglas Crockford did the thing you promised me never to do: he arrrred tee eff em. The sequel was surprising. He discovered – buried beneath JavaScript's modish curly brackets, sluttish comparison operators and baffling scoping rules – a peculiarly powerful language, that was quite different to the very many C-like scripting languages that pollute the programming ecosphere.

Crockford set about proving-by-doing. He showed, and published on his website, that it was possible to make JavaScript objects with private, hidden fields – a feat that the textbooks of the time implied was impossible. He separated his larger programs into properly independent modules (ditto).

He used JavaScript's object literals as the basis of his data-interchange format called "JSON" – that's the JSON that everybody now uses for everything – fully specified in a single, short webpage. (At this period, the shelves of Waterstones were groaning with thick, glib tomes – some heavy enough to restrain a self-closing fire door –  preaching the virtues of JSON's anointed rival, the unspeakable/unreadable XML.)

He created JSLint, a program that nudged its users towards the Crockford-blessed path of wholesome JavaScript, and famously and generously licensed "IBM, its customers, partners, and minions" to use this tool for evil.

verity stob portrait

Bjarne Again: Hallelujah for C++

READ MORE

Most of all, he wrote JavaScript: The Good Parts. This "cranky pamphlet" (description © D Crockford) was adopted by a sizeable constituency as JavaScript's nearest equivalent to K&R, or Stroustrup, or Klabnik and Nichols. It even had a Hello, World as its first program.

Eeyore's Gloomy Place

A decade on, thanks in large part to Crockford's contributions, the language's importance has increased n-fold. One consequence of this: of recent times, the language has suffered serial tampering, culminating in annual revisions to its standard. Good Parts has fallen obsolete.

How JavaScript Works is not a rework of Good Parts, but it is a product of the same basic approach. Crockford tours the language feature-by-feature: pointing out traps, rejecting facilities he regards as dangerous gewgaws, suggesting workarounds, recommending techniques.

It is, in the jargon of JavaScript blogs, an opinionated resource. "If I fail to mention your most favorite feature, it is most likely because that feature is crap." If he does mention it, you may yet regret it. These are just some of his unfavourite things:

  • Callbacks, promises and async/await – i.e. all three code-sequencing structures used by Node.js programmers ancient and modern. These Crockford styles as "the three mistakes"
  • ES6 generators ("added during the time when the standards process suffered from serious Python envy". Crockford's code snippet demonstrating an alternative looks so much neater and slicker, it should have the standards committee jointly slapping their foreheads and crying "D'oh!")
  • Rethrown exceptions ("a terrible practice that C++ made popular")
  • The fat arrow => ("Farts [sic] are an abbreviated way of writing functions". Given reasons for dislike: a problem with ambiguous braces when using a fat arrow to return an object, and the danger of confusing it with <= and >=. Really?)
  • The class keyword ("The coders using class will go to their graves never knowing how miserable they were")

There are some newer JS features that receive a warmer welcome: the Array.reduce method is rated as "kind of brilliant". But such enthusiasm is spent frugally.

Incidentally, the TypeScript language, the current toast of many of those fashionable React kids, Node-inventor Ryan Dahl, and indeed myself, is not mentioned. Given Mr Crockford's stated low opinion of type-safety ("Types can induce us to embrace cryptic, intricate, and dubious coding practices") and his italicised advice "Transpilers should never be used in production", I think we can safely assume that TypeScript is firmly buried in his "crap" pile.  Boo hoo.

Tigger bounces in

The book is by no means all gloom and doom; rather it is gloom and remedy.

Consider the early chapters. These deal with JavaScript's number type, which is based on 64-bit IEEE floating point numbers. Every few minutes, somewhere in the world, a naive JavaScripter falls into this hole

0.1 + 0.2 === 0.3  // false, obvs

so  it is reasonable of Crockford to highlight it. (On the other hand, I suspect his report of this wrinkle

(1 / 0) === (1 / -0)  // also false

is there just to amuse readers. Works for me.)

The next bit is smart: disapproving of a standard proposal to supplement number with a BigInt, he takes the bottom 24 bits of the ordinary doubles and tortures them into becoming the basis of an arbitrary-precision integer library. Not satisfied with this, he extends his integer library to make a "big floating point" library – cunningly fashioned so that tenths add up properly – and then takes it even further to create a "big rational" library that works with fractions, however vulgar.

It's all very ingenious... but building a model of the SS Titanic out of spent Vestas is ingenious too. And one worries about performance (of the arithmetic, not the matches). There again, my data sources rarely give me as many as 14 bits of precision on a sunny day; I dare say those doing financial calcs will be properly grateful.

This general approach sets the template: identify a problem in the language, then supply a workaround.

...but I'm not convinced the workaround is always needed. "Requestors" are the Crockford alternative to Node.js's callbacks, promises and async/await functions. That the first two are problematic is uncontroversial; but Crockford's objection to async/await, as I understand it, is that it conceals its underlying mechanism from its users, who consequently don't understand its workings.

This sounds to me like the old argument, long ago advanced by the pipe-smoking and leather elbow patch generation, that nobody should be allowed to use C until he or she has mastered Z80 assembly. I am not buying it. Also, miserable conservative that I am, I find myself reluctant to pioneer a fourth callback mechanism when my codebase is already riddled with a confusing mixture of the other three.

A much more promising innovation is JSCheck, a powerful variation on the usual unit testing framework. Instead of obliging the programmer to write tests one tedious assertEquals() at a time according to the lumpen prescription of the TDD crowd, JSCheck tests are configured using predicate functions that signal true when the results are good. When activated, the target code is bombarded with auto-generated random values. It looks much more like fuzzing than conventional unit tests, and I am looking forward to trying it in anger.

The book proper ends with a chapter based on the famous WAT talk by Gary Bernhardt (which in turn was surely influenced by Crockford's "Bad Parts" appendix in Good Parts). JavaScript's most perverse nooks are exposed. As ever, JavaScript's unjust equality operator and its empty arrays

[] == []       // false
[] == ![]      // true

provide hours of fun for the kids.

Tonstant Weader Doesn't Fwow Up

I stumbled upon How JavaScript Works by accident. The book has been out nearly a year. It has featured on no podcast of my earbudding. There is no Egghead course celebrating it, and at time of writing there is just wun rather sour review on amazon.co.uk.

Given the importance of JavaScript and the provenance of the book, this is surprising. I suspect that it was not published by a "known" imprint is part of the problem – indeed there are various signs of self-publication; the cover is decorated with a humorous headline: THE SHOCKING BLOCKBUSTER THAT DARES TO RIP THE LID OFF BEHIND THE SCENES!

Crockford has always been cheerfully iconoclastic, and he has always followed the Third Doctor's dictum about being serious of purpose, if not approach.

These are admirable qualities, but the unrelenting jokiness tends to fog the lens. He could do with an editor. My services are available, and are astonishingly good value. If taken up, I'll fix wun problem at wunce. ®

Verity Stob is the pseudonym of a software developer based in London. Since 1988, she has written her "Verity Stob" column for .EXE magazine, Dr. Dobb's Journal and, since 2002, The Register.

Sponsored: Beyond the Data Frontier

SUBSCRIBE TO OUR WEEKLY TECH NEWSLETTER




Biting the hand that feeds IT © 1998–2019