alert(typeof null) //alerts ‘object’
But wait, it gets even better!
Remember back in the day when you were first learning JS? You’ll remember NaN is Not-A-Number. You’ll get it returned to you if you, for example, 1) try to parse a non-number ( parseInt(“blabla”()), 2) a math operation where the result is not a real number ( Math.sqrt(-1)) and a couple of other cases.
So why is that when we call the “typeof” method on “NaN” we get “number”. Further, why is it that “NaN” is NOT strictly equal to itself?
alert( typeof NaN ) // alerts ‘Number’ alert( NaN === NaN ) // evaluates false
The ECMAScript standard states that Numbers should be IEEE-754 floating point data.* This includes Infinity, -Infinity, and also NaN.
Understanding why the statement “NaN === “NaN” evaluates to false is a little more subtle. First, we have to remember what the strict operator( === ) does. The strict operator compares both type and value.
What is the value of NaN (great interview question, BTW)? Well, NaN doesn’t have a real value. So if you compare it to itself, values cannot be compared and therefore the boolean value has to be “false.”
Last one for today:
alert( new Array() == false) // evaluates true
This is a good one--also quite the famous quirk in JS.
So we’ve made a new, empty array and using the loose equality operator to compare it to the boolean ‘false’. Why is that? An empty array is NOT defined as a falsey value**.
Here’s what happens: Under the hold, JS will coerce the new Array by calling .toString() on it. So what we’ll get is:
“” == false
which evaluates to true. An empty string is in fact a falsy value so the statement is true.
Those are just a few of the curiosities JS presents to make us scratch our heads, vex and for the geek in us--delight us.
Stay tuned for more.
In the meantime,
Keep Coding Out Your Dreams!
*The IEEE Standard for Floating-Point Arithmetic was established in 1985 and is a technical standard for floating-point arithmetic. Read all about it here
**Falsey values in JS are: 0, null, undefined, false, NaN and the empty string(“”).