How well do you know JavaScript?

| Comments

We all know JS somehow, how confident are you? Is NaN equal NaN? Is null equal 0? What is the result of adding two empty Arrays? If you know these ones, you’re really good, but still can find some more interesting JS facts by reading further. Let’s go!

Is NaN equal NaN?

Nope!

1
2
NaN === NaN
false

But wait, if NaN is not actually equal NaN, maybe we need some coercion to achieve the equality of these two quite similar things.

1
2
NaN == NaN
false

Not this time!

Trying to explain that: if you parseInt a string you’ll always get a NaN, regardless of the input. So when you parseInt two different strings, the result of both of them should not be equal. parseInt('WTF') is not the same NaN as parseInt('FTW'). Or I’m wrong :-)

What is the type of NaN?

As we all know NaN stands for Not a Number, so what is the type of NaN?

1
2
typeof(NaN)
"number"

Yes! It’s a number! :)

Trying to explain that: I think this just indicates the origin of NaN - it should be a number, but it’s not. Just the naming is a little bit mismatched here, but on the other hand, it fits the context quite well…

Is Infinity - Infinity equal 0?

Nope.

1
2
Infinity - Infinity == 0
false

This one is also interesting, but if you think about it, it actually makes sense… somehow. How Infinity can be measurable at all? It can be bigger than anything else, so can be bigger even than itself and thus this distraction might not so obviously equals 0 :)

Yes, that’s not so stupid, you think. So what about that?

1
2
Infinity == Infinity
true

What is the result of Infinity - Infinity then? Of course it’s NaN!

Trying to explain that: No way, it’s too much for me. Please help!

Null FTW!

This one is funny. Check it out:

1
2
3
4
5
6
null <= 0
true
null >= 0
true
null == 0
false

No comment!

Arrays and Hashes

What is the result of adding two empty Arrays? Of course it’s an empty String!

1
2
[]+[]
""

Hmmm, strange, and if we add an empty Array to an empty Object?

1
2
{}+[]
0

We’ll get 0, of course. Try to switch the items, and you’ll obviously get what you want.

1
2
[]+{}
"[object Object]"

Trying to explain that: I actually have no idea what could be possibly the desired result of the ones above, but it’s really strange we’re getting e.g. an empty String when adding two Arrays.

Wrap up

There’s not too much to sum up, really :-) What I can say is that I’m pretty sure there’s much more of these. Please let me know if you think I’ve missed something :-)

Comments