This challenge originates from my “Embrace Wacky JavaScript” presentation. I thought I could publish it in my blog and talk through some of this crazy logic.
|
|
There is a main
function and a globals
function. The main
’s function parent object will be bound to globals
and assigned to saying
. I could as well have used an apply
or call
method and pass in globals
as the first parameter.
In the function I have three variables: there are zero
, one
, and clearUp
. zero
and clearUp
variables are pretty straightforward. I’ll need to talk about the one
variable.
There are a couple sections. "" + ++zero
, !!"hello".length
, and [" ", "world"]
.
In "" + ++zero
, the first thing that happens is zero
variable is incremented by one. Then it is concatenated into an empy string, so the incremented value will be coerced as a string. This expression results "1"
.
In the next section (!!"hello".length
), .length
gets evaluated first, so the expression turns into !!5
. With the double bang operators, the number value is coerced into false
then true
.
So the expression for the one
variable is this, "1" + true + [" ", "world"]
. The plus signs here are concatenators, so every different datatype will be coerced into a string and attached to each other. The value assigned to the one
variable is "1true ,world"
. clearUp
variable removes the comma.
The remaining if
condition sees this.zero
from its parent object. That value is 0
. That value is falsey and fails the condition. Either way the same thing gets logged. I didn’t put much difference here.
Why
As I mentioned in my previous post, JS is just plain weird. So this was an exercise to try and see how weird and valid I can get JS. By all means, this code is very bad and impractical. If ever used I suspect it will confuse some developers greatly.