Without looking it up, can you tell me what you'd get if you tried to add two empty arrays together in JavaScript?

[] + [];
  1. An empty array ([])
  2. An empty object ({})
  3. An empty string ('')
  4. Zero (0)

This is one of the questions we had in a work quiz last week, taken from the classic 'wat' talk. It's a good laugh if you haven't seen it before.

The answer? An empty string.

This might seem weird if you're used to statically-typed languages, but it makes sense when you break it down. What's happening here is called type coercion.

When you try to add two arrays together, the JavaScript interpreter coerces the arrays into strings. It does this by calling the Array.prototype.toString() method automatically on each array. It then concatenates these strings, and of course, adding two empty strings together results in another empty string.

// Adding two empty arrays:

[] + [];

// Is like adding two empty strings:

'' + '';

// Because this is what really happens:

[].toString() + [].toString();

It's more obvious when the arrays have values:

[52] + [' cards']; // '52 cards'

It's fashionable to hate JavaScript for its quirks, but I love it! Every time I come across something like this, I'm grateful for the opportunity to gain a deeper understanding of the language.

A lot of developers love TypeScript because it catches these quirks at compile time. It even powers the IntelliSense for JavaScript in Visual Studio Code! I still think it's important to have a good understanding of vanilla JavaScript, though. That's what actually runs in the browser!

That being said, I've started learning TypeScript for my job, and it's great. My friend Charles Roper recommended TypeScript in 50 Lessons. Definitely check it out if you're interested in learning TypeScript!


Thanks for reading. If you have any feedback, feel free to shoot me an email.