Search code examples
javascriptarraysstringsumconcatenation

Why array + array returns a string?


Why does summing 2 arrays joins everything in a string, concatenating the first and last values:

  let array = [1, 2]

  let array2 = [3, 4]

  let array3 = array + array2

  console.log(array3) // 1,23,4

Solution

  • That's just how JavaScript works. Both are objects, there's not a defined thing for + between an Array and an Array, so it does the default thing of converting to String and concatenating them (still as a String).

    Use the Array.prototype.concat method to acheive your goal.

    let array = [1, 2]
    
    let array2 = [3, 4]
    
    let array3 = array.concat(array2);
    
    console.log(array3) // [1, 2, 3, 4]

    Alternatively, you can use the spread operator:

    let array = [1, 2]
    
    let array2 = [3, 4]
    
    let array3 = [...array, ...array2];
    
    console.log(array3) // [1, 2, 3, 4]