by

Weird JavaScript: Why do you get an empty string when you add arrays?

Reading Time: 2 minutes

I’m going to have an occasional series about weird stuff in JavaScript. Let’s kick this off with a weird question:

Why is it that when you have [] + [], you get an empty string ('') ? Isn’t this against the law?

array plus array equals empty string
But why were we adding arrays in the first place?

In JavaScript, the + operator has two jobs

Job #1: Addition

console.log(2 + 3); // 5
console.log(256 + 256);// 512

Here you see that the addition operator has produced a sum of numeric operands.

Job #2: String Concatenation

console.log('foo' + 'bar') // 'foobar
console.log('hello' + ' ' + 'world'); // 'hello world'

Here, the + has concatenated strings.

This by the way is common in many languages. Java, C#, and Python all have the + perform double-duty as a numeric sum operator and a string concatenator.

JavaScript will coerce values in order to avoid errors

What happens when you try to concatenate something that isn’t a string?

This one might feel obvious:

console.log(2 + 'foo'); // 2foo

That feels obvious because one thing is definitely a number and another definitely isn’t.

But here’s one that can feel confusing:

console.log(2 + '3'); // '23'

The reasoning for this one is the exact same as the reasoning for the first one: JavaScript coerced the non-string into a string, and then concatenated.

This is not common to other languages. Other languages throw errors when you mix in types.

So is [] + [] addition or concatenation?

It’s not addition — it’s concatenation.

Before JavaScript can concatenate, it has to make sure everything is a string.

So each array gets coerced into a string, and then the two strings are concatenated.

It would be more obvious if those arrays had values:

console.log(['foo'] + ['bar']); // 'foobar'
console.log(['foo', 'bar'] + ['baz']) ; // 'foo,barbaz'

Now that you can see what happens when arrays with values get concatenated, it should be a little more clear what happens when empty arrays get concatenated, too:

console.log([] + []); // ''

TL;DR

You’re not adding empty arrays. You’re concatenating them. JavaScript will coerce non-strings into strings in order to concatenate successfully. Two empty strings concatenated still make an empty string.

Leave a Reply

You don't have to register to leave a comment. And your email address won't be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.