DEV Community


Posted on

Javascript: Why do we get empty strings, when we compare them to empty arrays?

console.log([] == []) // ""

Enter fullscreen mode Exit fullscreen mode

The output of the code console.log([] + []); will be an empty string "".

This behaviour can be a bit surprising at first, but it's due to the way JavaScript handles the addition operator (+) when used with arrays.

When you try to add two arrays together using +, JavaScript converts the arrays to strings and then concatenates those strings. An empty array, when converted to a string, produces an empty string. So, when you add two empty arrays together, you get the concatenation of two empty strings, which is just an empty string "".

In other words, [] + [] is equivalent to "" + "", which evaluates to "".

It's important to be aware of this behaviour when working with arrays in JavaScript, as it can lead to unexpected results.

If you want to concatenate two arrays, you can use the concat() method instead. For example, [1, 2].concat([3, 4]) it would return a new array [1, 2, 3, 4].

Top comments (0)