JS Weirdness: Type Combinations that Make PERFECT Sense

Jordan Panasewicz
Enlear Academy
Published in
2 min readAug 16, 2021

--

Today we’re going to have a little fun looking at how JavaScript handles certain type combinations. This is something that I found intriguing after working entirely with TypeScript for the past few weeks.

First, let’s take a look at some examples, take a moment to think about what the obvious answer is (or should be)… then we’ll dive into the actual answers.

QUESTIONS: PART A
1) [] + [] = ?
2) [] + {} = ?
3) {} + [] = ?
4) {} + {} = ?

Got your answers ready??? Let’s take a look:

  1. While it’s obvious that an empty array plus an empty array should be some sort of empty array(s)… it’s actually:
"" aka an empty string..? What?!

2. An empty array and an empty object.. this one is even less obvious:

[object Object]

3. Now let’s flip the order, and see what we get when we add an empty object and an empty array.. surely it’s the same as number 2? Let’s see:

0

4. And this one is actually the only one that ends up with a correct answer.. but an object plus an object isss an object? Nope.. its:

NaN

Now that last one is actually true, but surely not what we were expecting.

Let’s take a look at some more cases and get a little weirder with these ones:

1) Array(16) = ?
2) Array(16).join("wat") = ?
3) Array(16).join("wat" + 1) = ?
4) Array(16).join("wat" - 1) + " Batman!" = ?

Alright.. you surely know all these ones right?!?

  1. Array(16) is a simple one.. it creates an array of 16 items:
,,,,,,,,,,,,,,,,

2) Now if we join those items with a “wat”, we simply get:

watwatwatwatwatwatwatwatwatwatwatwatwatwatwatwat

3) And while that is surely super neat, what if we add 1 to the “wat”??

wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1

4) Aaaand now for the kicker.. I gave you a hint with the “ Batman!”… but what happens if we actually subtract 1 from the “wat” instead?!?

NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Batman!

Hahahahah! That’s all for now — I hope you had as much fun with this one as I did!

--

--