The incredible complexity of Javascript's if
Conditional branching... The most fundamental construct in all of programming, the most common of them, the simplest of control flows, the first one to learn, and the basis of all machine learning.
Its importance is hard to overestimate.
But have you ever thought about what really happens when a language interpreter encounters an if statement?
The answer hugely depends on the language, of course.
So first, the strongly-typed ifs.
In case of those, the interpreter needs to check if the condition evaluates to "true" or "false",
and execute either the first or the second alternative based on that. Simple.
Going into what's called truthy ifs, we have Lisp-type ifs.
Lisp interpreters only need to check for a "false" value, since everything else is considered "true".
Sounds like not a big deal, but these kinds of ifs are technically more expressive than the strongy-typed version.
A variation of truthy if is the C-type if.
Here we need to check if what's inside the brackets is zero, then execute the second branch in case it is, otherwise execute the first branch.
There is a catch though -- what is zero exactly? Is 0.0 a zero? Is -0.0 a zero? It makes sense for them to be.
In C specifically, there are 3 flavors of zero -- the integer 0 (int, unsigned long, ...),
the floating point 0.0 and 0.0f, and the NULL pointer.
We can say that all 3 types of zero are coersible to "false" in C.
This brings us to the Final Boss, the master of coersions, Javascript.
Not only does the Javascript have the usual false, null and undefined, but also 0, -0, 0n, NaN, "", and the cherry on top, the document.all.
If you think it's absurd to do a whole 9 checks every time an if is encountered,
you should know that most dynamic languages do something similar:
- Lua does 2
- Ruby does 7
- Pearl does 7
- PHP does 8
- Python does 9
return home