Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)
This handy operator is a trouble maker.

TL;DR: Don't mix booleans with non-booleans.
Problems
Not Declarative Code
Hard to debug
Magic Castings
Accidental Complexity
Solutions
Be Explicit
Don't mix Booleans with non-booleans.
Be Smarter than your compiler.
Stay loyal to the bijection.
Sample Code
Wrong
Right
Detection
Since this is a "feature" in some languages it would be hard to test. We can set programming policies or choose more strict languages.
We should detect ! !! usages in non-boolean objects and warn our programmers.
Tags
Casting
Coercion
Javascript
Conclusion
Languages like JavaScript divide their whole universe into true or false values. This decision hides errors when dealing with non booleans.
We should be very strict and keep booleans (and their behavior), far away from non booleans.
Relations
More info
Credits
Photo by Greg Rakozy on Unsplash
It is easier to write an incorrect program than understand a correct one.
Alan J Perlis
This article is part of the CodeSmell Series.
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionYou might be interested in this. Using the boxed version Boolean can yield unpredictable results. What's your take on using boxed vs. primitives? Are there any use cases for boxed over primitives in JavaScript?
See this bug found in Jest. It's a pretty crazy bug.
const s1 = new Set([false, true]);
const s2 = new Set([new Boolean(true), new Boolean(true)]);
expect(s1).not.toEqual(s2); // success
expect(s2).not.toEqual(s1); // failure
// expect(received).not.toEqual(expected)
// Expected: Set {false, true}
// Received: Set {{}, {}}const s1 = new Set([false, true]);
Code Smells
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.





