Java Script Interview Secret : console.log([1, 2] + [3, 4]);

Robert Clave
1 min readJun 26, 2024
java script tips

What Does This Code Output?

console.log([] + []);

Did you think of an answer immediately? Hold on before you respond. This seemingly simple question often trips up even seasoned developers. Let’s break it down and explore the concepts behind it.

Here’s what happens:

  1. Array to String Conversion: Both arrays are converted to strings. The default behavior for converting an array to a string is to join its elements with a comma. Since both arrays are empty, they convert to empty strings.
  2. String Concatenation: The + operator then concatenates these two empty strings.

So, [] + [] results in '' (an empty string).

Common Misunderstandings

  1. Numeric Addition: Many assume that adding arrays would somehow involve numeric addition, but since arrays are objects, JavaScript resorts to type coercion.
  2. Undefined or Errors: Some might think the operation would result in an error or undefined, but JavaScript's type coercion is quite permissive.

Practical Implications

Understanding this behavior is crucial for debugging and writing clear, predictable code. This type coercion can lead to unexpected results in more complex expressions. For instance:

console.log([1, 2] + [3, 4]); // Outputs: '1,23,4'

Here, both arrays are first converted to strings ('1,2' and '3,4'), and then concatenated into '1,23,4'.

--

--

Robert Clave

Just another human compiler, converting thoughts to code