Javascript Bang Bang Yuck

We had a brief discussion at work about using !! vs Boolean() in Javascript to coerce a value to a boolean. It seemed some of my coworkers could not quite get why I favor Boolean (and in fact really dislike !!). Let’s see if I can make it clear.

I fully understand the need to for devs working in Javascript (or any language) to learn to recognize and strive to understand some of the frequently used idioms in those environments. However, I find many of the idioms unclear unless you are deeply adept in the language. They are especially dense to someone at the novice or even journeyman level of experience. In addition, I find some of the idioms fundamentally offensive to my conception of meaningful code construction.

So, !!somevalue is an idiom to force some truthy1 value into an explicity true or false value (i.e. a Boolean). This idiom offends me because I read it as redundant: take a true value to a false value back to a true value. Seems pointless (unless you really grasp truthy).

This idiom makes the code unclear on the intent of the code (i.e. to coerce the value). I much prefer to be explicit in what you are intending in these cases. Explicity code in that you are coercing the value into a specific type: Boolean(somevalue). This is both clear to me as to the intent of the code and does not bring to mind the offensiveness of something that appears redundant.

// I do not like this
const offensive_coersion = !!someFunctionThatReturnsTruthy()

//I prefer this
const obvious_coersion = Boolean(someFunctionThatReturnsTruthy())

Idioms happen. They tend to evolve among those Adepts with deep experience in a language. Some idioms are really useful. They make the code more concise while also making it more clear; uses of map and reduce operations demonstrate this attribute. Many idioms make the code more concise, but make it much harder to understand the intent. This primarily hampers those who are not the deep Adepts (I am not a Deep Adept in Javascript yet). Those folks happen to be the ones usually doing most of the maintenance and extensions to our systems. We should not build so that only the experts can understand the implementations. If an idiom does not make the intent of the code explicitly clear, it should be avoided.

This applies to idioms in all languages. I am not intending to bag on Javascript here, but the practice of using dense idioms that make code less clear. I hold the same opinion for most List Comprehensions in Python, for any but the most simple uses of Ternary operators in any language, and for passing anonymous functions (i.e. lambdas or rocket-functions) as arguments. In these examples, code them out in a named function or assign the object to a nicely named variable to make its intent clear, then use that instead.

  •   `truthy` is another offensive concept in Javascript, but that is another tale for another day.