Escaping the Boolean Trap in JS

— 3 minute read

The Boolean Trap refers to a common mistake when writing APIs in which you use booleans as input parameters and the code becomes unreadable.

NodeJS has an example in url.parse

url.parse('example.com', true, false);

Here's an example that jQuery is looking to solve.

$('.thing').animate(...).stop(true, false);

What the hell does .stop(true, false) mean?!

Usually as caller of this API you're stuck with either the above unreadable code, or you add some extra variables in that clarify the purpose of the boolean. Something like:

var clearQueue = true, jumpToEnd = false;
$('.thing').stop(clearQueue, jumpToEnd);

But sometimes there are advantages to dynamic typing. In JS, I'm a fan of

$('.thing').stop('clearQueue', !'jumpToEnd');

Or in the Node case

url.parse('example.com', 'parseQuery', !'slashesDenoteHost');

The purpose of the parameter is clear and the value of the parameter is clear. You can clarify the type by wrapping the params with Boolean('clearQueue') or similar if it makes you feel better.

Further reading: permalink