Why is [1,2] + [3,4] = "1,23,4" in JavaScript?

The JavaScript's + operator is used to add two numbers or join two strings. However, when used with arrays, it doesn't concatenate them as you might expect. Instead, it converts both arrays to strings and then concatenates those strings.

What Happens with [1,2] + [3,4]

When JavaScript encounters the + operator between two arrays, it follows these steps:

  1. Convert each array to a string using the toString() method
  2. Concatenate the resulting strings
// Step 1: Arrays are converted to strings
console.log([1,2].toString());  // "1,2"
console.log([3,4].toString());  // "3,4"

// Step 2: String concatenation
console.log("1,2" + "3,4");     // "1,23,4"

// The complete operation
console.log([1,2] + [3,4]);     // "1,23,4"
1,2
3,4
1,23,4
1,23,4

Type Coercion in Action

This behavior is due to JavaScript's type coercion. When using + with non-primitive types, JavaScript calls the valueOf() method first, then toString() if needed:

let arr1 = [1, 2];
let arr2 = [3, 4];

console.log("arr1.valueOf():", arr1.valueOf());
console.log("arr1.toString():", arr1.toString());
console.log("Result:", arr1 + arr2);
arr1.valueOf(): [ 1, 2 ]
arr1.toString(): 1,2
Result: 1,23,4

Proper Array Concatenation

To properly join two arrays, use the concat() method instead:

let result1 = [1, 2].concat([3, 4]);
console.log("Using concat():", result1);

// ES6 spread operator (alternative)
let result2 = [...[1, 2], ...[3, 4]];
console.log("Using spread:", result2);
Using concat(): [ 1, 2, 3, 4 ]
Using spread: [ 1, 2, 3, 4 ]

Comparison

Method Result Type Example Result
[1,2] + [3,4] String "1,23,4"
[1,2].concat([3,4]) Array [1,2,3,4]
[...[1,2], ...[3,4]] Array [1,2,3,4]

Conclusion

The + operator with arrays results in string concatenation due to type coercion. Use concat() or the spread operator for proper array concatenation instead.

Updated on: 2026-03-15T23:18:59+05:30

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements